R - list to data frame

2018-12-31 05:54发布

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
)

标签: r list dataframe
18条回答
人间绝色
2楼-- · 2018-12-31 06:20

test1 <- list( c(a='a',b='b',c='c'), c(a='d',b='e',c='f')) as.data.frame(test1) a b c 1 a b c 2 d e f

test2 <- list( c('a','b','c'), c(a='d',b='e',c='f'))

as.data.frame(test2) a b c 1 a b c 2 d e f

test3 <- list('Row1'=c(a='a',b='b',c='c'), 'Row2'=c(a='d',var2='e',var3='f'))

as.data.frame(test3) a b c var2 var3 Row1 a b c
Row2 d e f

查看更多
一个人的天荒地老
3楼-- · 2018-12-31 06:23

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)
查看更多
倾城一夜雪
4楼-- · 2018-12-31 06:23

data.frame(t(sapply(mylistlist,c)))

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

查看更多
深知你不懂我心
5楼-- · 2018-12-31 06:23

For the general case of deeply nested lists with 3 or more levels like the ones obtained from a nested JSON:

{
"2015": {
  "spain": {"population": 43, "GNP": 9},
  "sweden": {"population": 7, "GNP": 6}},
"2016": {
  "spain": {"population": 45, "GNP": 10},
  "sweden": {"population": 9, "GNP": 8}}
}

consider the approach of melt() to convert the nested list to a tall format first:

myjson <- jsonlite:fromJSON(file("test.json"))
tall <- reshape2::melt(myjson)[, c("L1", "L2", "L3", "value")]
    L1     L2         L3 value
1 2015  spain population    43
2 2015  spain        GNP     9
3 2015 sweden population     7
4 2015 sweden        GNP     6
5 2016  spain population    45
6 2016  spain        GNP    10
7 2016 sweden population     9
8 2016 sweden        GNP     8

followed by dcast() then to wide again into a tidy dataset where each variable forms a a column and each observation forms a row:

wide <- reshape2::dcast(tall, L1+L2~L3) 
# left side of the formula defines the rows/observations and the 
# right side defines the variables/measurements
    L1     L2 GNP population
1 2015  spain   9         43
2 2015 sweden   6          7
3 2016  spain  10         45
4 2016 sweden   8          9
查看更多
深知你不懂我心
6楼-- · 2018-12-31 06:26

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

查看更多
人气声优
7楼-- · 2018-12-31 06:28

assume your list is called L,

data.frame(Reduce(rbind, L))
查看更多
登录 后发表回答