juan wang juan wang - 2 months ago 25
R Question

R - Convert nested list into dataframe

I saw similar questions answered in stackoverflow, but I couldn't find the way to fit my specific situation, so I open a new one.

My goal is to convert a nested list like this:

a:list of 2
..$ time: num[1:5] 1 2 3 4 5
..$ int: num[1:5] 6 7 8 9 0

b:list of 2
..$ time: num[1:5] 1 2 3 4 5
..$ int: num[1:5] 6 7 8 9 0


into a dataframe like this:

Name time int
a 1 6
a 2 7
.
.
.
b 1 6
...


I tried to use melt in reshape2 and I got time and int as the values in one column(L2). Something like this:

Value L2 L1
1 time a
2 time a
.
.
.
6 int a
.
.
.

Answer

You can use ldply from plyr package

library(plyr)
ldply(lst, data.frame, .id = "Name")

Taking dummy data from @SymbolixAU 's answer, you have the output as

#  Name time int
#1   a    1   5
#2   a    2   6
#3   a    3   7
#4   b    1   1
#5   b    2   2
#6   b    3   3
#7   b    4   4