R list to 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?

I am new to R, so I figure there is probably an easy way to do this. I searched here on Stack Overflow and couldn't find a similar question, so I apologize if I missed it. Some sample data:

l <- replicate(
  132,
  list(sample(letters, 20)),
  simplify = FALSE
)

Assuming your list of lists is called l :

df <- data.frame(matrix(unlist(l), nrow=132, byrow=T))

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=T),stringsAsFactors=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).


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.

链接地址: http://www.djcxy.com/p/70904.html

上一篇: 将数据框的列拆分为多个列

下一篇: R列表到数据帧