r - Convert a list to a data frame

ID : 3522

viewed : 130

Tags : rlistdataframer

Top 5 Answer for r - Convert a list to a data frame

vote vote


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).

vote vote


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) 
vote vote


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.

vote vote


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:


sapply converts it to a matrix. data.frame converts the matrix to a data frame.

resulting in:

enter image description here

vote vote


assume your list is called L,

data.frame(Reduce(rbind, L)) 

Top 3 video Explaining r - Convert a list to a data frame