I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a quick way to convert this structure into a data frame that has 132 rows and 20 columns of data?
Here is some sample data to work with:
l <- replicate(
132,
list(sample(letters, 20)),
simplify = FALSE
)
test2 <- list( c('a','b','c'), c(a='d',b='e',c='f'))
test3 <- list('Row1'=c(a='a',b='b',c='c'), 'Row2'=c(a='d',var2='e',var3='f'))
Assuming your list of lists is called
l
:The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:
data.frame(t(sapply(mylistlist,c)))
sapply
converts it to a matrix.data.frame
converts the matrix to a data frame.For the general case of deeply nested lists with 3 or more levels like the ones obtained from a nested JSON:
consider the approach of
melt()
to convert the nested list to a tall format first:followed by
dcast()
then to wide again into a tidy dataset where each variable forms a a column and each observation forms a row:With
rbind
Edit: Previous version return
data.frame
oflist
's instead of vectors (as @IanSudbery pointed out in comments).assume your list is called
L
,