I have a list of data frames, and I'm looking to assign to each data frame within the list a variable column that is simple a character vector of the given dataframe's name.
data <- list(
d1 = data.frame(animal = sample(c("cat","dog","bird"), 5, replace = T)),
d2 = data.frame(animal = sample(c("cat","dog","bird"), 5, replace = T)),
d3 = data.frame(animal = sample(c("cat","dog","bird"), 5, replace = T))
)
This yields:
> data
$d1
animal
1 cat
2 bird
3 cat
4 cat
5 cat
$d2
animal
1 dog
2 cat
3 cat
4 cat
5 bird
$d3
animal
1 cat
2 dog
3 cat
4 cat
5 cat
What I want to do is create something like the following:
> newdata
$d1
animal newvar
1 cat d1
2 cat d1
3 cat d1
4 dog d1
5 cat d1
$d2
animal newvar
1 bird d2
2 cat d2
3 bird d2
4 cat d2
5 cat d2
$d3
animal newvar
1 bird d3
2 bird d3
3 cat d3
4 cat d3
5 bird d3
But I can't quite figure out how to actually reference the data frame name --in a list of data frames-- and turn it into a character vector appropriately.
Something like the following does not work:
namefunc <- function(x) {
x <- x %>% transform(newvar = as.character(x))
}
newdata <- namefunc(data)