Convert a list to a data frame
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,
as.list(sample(letters, 20)),
simplify = FALSE
)
With rbind
do.call(rbind.data.frame, your_list)
Edit: Previous version return data.frame
of list
's instead of vectors (as @IanSudbery pointed out in comments).
Update July 2020:
The default for the parameter stringsAsFactors
is now default.stringsAsFactors()
which in turn yields FALSE
as its default.
Assuming your list of lists is called l
:
df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE))
The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:
df <- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE)
You can use the plyr
package.
For example a nested list of the form
l <- list(a = list(var.1 = 1, var.2 = 2, var.3 = 3)
, b = list(var.1 = 4, var.2 = 5, var.3 = 6)
, c = list(var.1 = 7, var.2 = 8, var.3 = 9)
, d = list(var.1 = 10, var.2 = 11, var.3 = 12)
)
has now a length of 4 and each list in l
contains another list of the length 3.
Now you can run
library (plyr)
df <- ldply (l, data.frame)
and should get the same result as in the answer @Marek and @nico.
Fixing the sample data so it matches the original description 'each item is a list of length 20'
mylistlist <- replicate(
132,
as.list(sample(letters, 20)),
simplify = FALSE
)
we can convert it to a data frame like this:
data.frame(t(sapply(mylistlist,c)))
sapply
converts it to a matrix.
data.frame
converts the matrix to a data frame.
resulting in:
assume your list is called L
,
data.frame(Reduce(rbind, L))