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)))