How to add list names in df as a column in data frame

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) #This return colnames. return(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 
+5
source share
1 answer

We can use Map to cbind each data.frame in a list with a corresponding name list .

 Map(cbind, list, name=names(list)) #$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 

The best option would be rbindlist to create a single dataset.

 library(data.table) rbindlist(list, idcol="name") 
+5
source

Source: https://habr.com/ru/post/1247193/


All Articles