Search code examples
rlistdataframetypeconverter

How to convert list of dataframe to dataframe which has a new column show the name of list in R


I have a list of data frame, for each list, I have a name for it, which is the USERID, the following is a sample of the list:

$'AAAAAA'
AA  BB  CC
a   b   1
c   d   2
e   f   3
S'BBBBBB'
AA  BB  CC
g   h   1
i   j   2
k   l   3

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

AA  BB  CC  USERID
a   b   1   AAAAAA
c   d   2   AAAAAA
e   f   3   AAAAAA
g   h   1   BBBBBB
i   j   2   BBBBBB
k   l   3   BBBBBB

Any Idea how it could be done. Thank you so much in advance


Solution

  • Since cbind recycles its arguments to the length of the longest vector, you could try

    Reduce(rbind, Map(cbind, x, USERID = names(x)))
    #   AA BB CC USERID
    # 1  a  b  1  AAAAA
    # 2  c  d  2  AAAAA
    # 3  e  f  3  AAAAA
    # 4  g  h  1  BBBBB
    # 5  i  j  2  BBBBB
    # 6  k  l  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"))