Converting a list into a data frame at each level goes into a single column

advertisements

I have a list of vectors as in the example

l=list(a=c("AA","AAA"),b=c("BB","BBB","BBBB"),c=c("CC"))

What I want is to generate a data frame with two columns. One contains the first level and the second contains the second level. for example I need this output

df=data.frame(fst=c(rep("a",2),rep("b",3),rep("c",1)),snd=c("AA","AAA","BB","BBB","BBBB","CC"))

what I did is, I converted the list into a wide formatted data frame and then melted it using reshape2 package as in the following:

library(plyr)
library(reshape2)
df=ldply(l,data.frame)
df_wanted=melt(df2,id.vars=".id",na.rm=TRUE)

so this has enabled me to get the needed results (still needs minor processing) but I was wondering if there is an easier solution to directly convert the list to the df_wanted format because in my case dfwill result in huge number of columns. Thank you so much for your comments.


You can use the basic stack command

setNames(stack(l), c("snd","fst"))

#    snd fst
# 1   AA   a
# 2  AAA   a
# 3   BB   b
# 4  BBB   b
# 5 BBBB   b
# 6   CC   c