How to convert a dataframe list to a dataframe that has a new column, displays the list name in R

I have a list of data frames, for each list I have a name for it, that is, USERID, the following example list:

$'AAAAAA' AA BB CC ab 1 cd 2 ef 3 S'BBBBBB' AA BB CC gh 1 ij 2 kl 3 

My question is how to convert this list to a data frame that has a new column showing USERID, like the example below:

 AA BB CC USERID ab 1 AAAAAA cd 2 AAAAAA ef 3 AAAAAA gh 1 BBBBBB ij 2 BBBBBB kl 3 BBBBBB 

Any idea how to do this. Thank you so much in advance

+5
source share
3 answers

Since cbind processes its arguments to the length of the longest vector, you can try

 Reduce(rbind, Map(cbind, x, USERID = names(x))) # AA BB CC USERID # 1 ab 1 AAAAA # 2 cd 2 AAAAA # 3 ef 3 AAAAA # 4 gh 1 BBBBB # 5 ij 2 BBBBB # 6 kl 3 BBBBB 

where x is

 structure(list(AAAAA = structure(list(AA = c("a", "c", "e"), BB = c("b", "d", "f"), CC = 1:3), .Names = c("AA", "BB", "CC"), class = "data.frame", row.names = c(NA, -3L)), BBBBB = structure(list( AA = c("g", "i", "k"), BB = c("h", "j", "l"), CC = 1:3), .Names = c("AA", "BB", "CC"), class = "data.frame", row.names = c(NA, -3L))), .Names = c("AAAAA", "BBBBB")) 
+6
source

Another way using the tidyr development tidyr :

 # install.packages("devtools") devtools::install_github("hadley/tidyr") library(tidyr) unnest(mylist, USERID) # USERID AA BB CC # 1 AAAAA ab 1 # 2 AAAAA cd 2 # 3 AAAAA ef 3 # 4 BBBBB gh 1 # 5 BBBBB ij 2 # 6 BBBBB kl 3 
+6
source

Or (if l is your list)

 library(data.table) rbindlist(Map(cbind, l, USERID = names(l))) # AA BB CC USERID # 1: ab 1 AAAAAA # 2: cd 2 AAAAAA # 3: ef 3 AAAAAA # 4: gh 1 BBBBBB # 5: ij 2 BBBBBB # 6: kl 3 BBBBBB 
+4
source

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


All Articles