Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

Is there a better way to add names of list fields (data frames in general) as a column of data frame?

Example data

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

It's working, but I want to avoid for loops when possible.

 for (i in 1:length(list)) {
     list[[i]][,"name"] <- names(list[i])
    }

What I'm trying:

lapply(list, FUN = function(df){
  df$anothername <- names(list$df) #This return colnames.
  return(df)
})

Output i want to get:

$DF1
  x y name
1 1 3  DF1
2 2 4  DF1
3 3 5  DF1

$DF2
  x y name
1 1 3  DF2
2 2 4  DF2
3 3 5  DF2

$DF3
  x y name
1 1 3  DF3
2 2 4  DF3
3 3 5  DF3
like image 298
M. Siwik Avatar asked Apr 15 '16 08:04

M. Siwik


1 Answers

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

Map(cbind, list, name=names(list))
#$DF1
#  x y name
#1 1 3  DF1
#2 2 4  DF1
#3 3 5  DF1

#$DF2
#  x y name
#1 1 3  DF2
#2 2 4  DF2
#3 3 5  DF2

#$DF3
#  x y name
#1 1 3  DF3
#2 2 4  DF3
#3 3 5  DF3

A better option would be rbindlist to create a single dataset.

library(data.table)
rbindlist(list, idcol="name")
like image 75
akrun Avatar answered Nov 14 '22 23:11

akrun