0
votes

I have a named list of data frames. I need to create a new variable for each data frame with the name of the data frame so I can eventually rbind them all to make the statistics and plots.

I know lapply doesn't pass the object's name and that there are plenty of posts with similar issues but I just can't adapt any of the solutions that I've seen to my particular problem.

This is what I've first tried but obviously doesn't work because names(x) is not returning the object's name.

TestList <- list(a = data.frame(Var1 = 1:5, Var2 = 5:1), b = data.frame(Var1 = 6:10, Var2 = 10:6))

lapply(TestList, function(x, y = names(x)){x$Var3 <- y; return(x)})

I have also tried with seq_along but then I'm lost on how to create the new variable for each data frame.

Does lapply pass an index? If so I could create a new object with

names(TestList)

and then source the name from there. I couldn't find how to do this either.

Finally this is what I would need to obtain:

DesiredTestList <- list(a = data.frame(Var1 = 1:5, Var2 = 5:1, Var3 = rep("a", 5)), b = data.frame(Var1 = 6:10, Var2 = 10:6, Var3 = rep("b", 5)))

2
A few things here are very unclear. You try to return z, but z has never been defined. Plus you want to add a third variable to the dataframes that holds the column names of the data frames. But names(a) and names(b) will only return c("Var1","Var2") while the data frames have 5 observations. Please clarify what your expected output is.mrz1702
Sorry for the mistake. Where there was a "z" there should have been an "x". I have also included the desired final list that I would like to obtain. I have fixed the errors. Also you are right about the output of names() function. If use names on TestList I would get "a" and "b" which is what I need. But if I apply the names function in lapply I get "Var1" and "Var2". I understand this is because lapply passes only the data frame to the function but I don't know how to go around this.netlak

2 Answers

0
votes

For the final data frame I need I've found a much easier solution

bind_rows(TestList, .id = "Var3")
0
votes

I got it working. I just wished lapply would pass the object's name to the function. Anyway, here is the way I got it working:

GotTheTestList <- lapply(seq_along(TestList), function(x){TestList[[x]]$Var3 <- names(TestList)[x]; return(TestList[[x]])})