Is there a better way to add list field names (data frames in general) as a column of a data frame?
Data examples
df1 <- data.frame(x = 1:3, y = 3:5) df2 <- data.frame(x = 1:3, y = 3:5) df3 <- data.frame(x = 1:3, y = 3:5) list = list() list[["DF1"]] <- df1 list[["DF2"]] <- df2 list[["DF3"]] <- df3
This works, but I want, if possible, to avoid loops.
for (i in 1:length(list)) { list[[i]][,"name"] <- names(list[i]) }
What am I trying:
lapply(list, FUN = function(df){ df$anothername <- names(list$df)
The output I want to get is:
$DF1 xy name 1 1 3 DF1 2 2 4 DF1 3 3 5 DF1 $DF2 xy name 1 1 3 DF2 2 2 4 DF2 3 3 5 DF2 $DF3 xy name 1 1 3 DF3 2 2 4 DF3 3 3 5 DF3
source share