2

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)

2 Answers 2

4

We can use Map to cbind the corresponding list elements of 'data' with the names of 'data'

Map(cbind, data, newvar= names(data))
Sign up to request clarification or add additional context in comments.

Comments

1
lapply(names(data), function(d) transform(data[[d]], newvar=d))

or eventually:

L <- lapply(names(data), function(d) transform(data[[d]], newvar=d))
names(L) <- names(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.