我有一个嵌套的数据列表。它的长度是132,每一项是一个长度为20的列表。是否有一种快速的方法可以将这种结构转换为具有132行和20列数据的数据帧?

下面是一些示例数据:

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

当前回答

更多的答案,以及这个问题的答案中的时间: 将列表转换为数据帧的最有效方法是什么?

最快的方法,不产生一个数据框架与列表,而不是向量的列似乎是(从马丁摩根的回答):

l <- list(list(col1="a",col2=1),list(col1="b",col2=2))
f = function(x) function(i) unlist(lapply(x, `[[`, i), use.names=FALSE)
as.data.frame(Map(f(l), names(l[[1]])))

其他回答

对于像从嵌套JSON中获得的3级或更多级别的深度嵌套列表的一般情况:

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

考虑一下melt()将嵌套列表转换为高格式的方法:

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

接着是dcast(),然后再次扩大到一个整洁的数据集,其中每个变量组成一个a列,每个观察值组成一行:

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

或者你可以使用tibble包(来自tidyverse):

#create examplelist
l <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)

#package tidyverse
library(tidyverse)

#make a dataframe (or use as_tibble)
df <- as_data_frame(l,.name_repair = "unique")



一个简短的(但可能不是最快的)方法是使用基底r,因为数据帧只是一个长度相等的向量的列表。因此,你的输入列表和一个30 x 132 data.frame之间的转换将是:

df <- data.frame(l)

从这里我们可以将其转置为132 x 30的矩阵,并将其转换回数据帧:

new_df <- data.frame(t(df))

一句话:

new_df <- data.frame(t(data.frame(l)))

行名看起来很讨厌,但是您总是可以用

行名称(new_df) <- 1:nrow(new_df)

更多的答案,以及这个问题的答案中的时间: 将列表转换为数据帧的最有效方法是什么?

最快的方法,不产生一个数据框架与列表,而不是向量的列似乎是(从马丁摩根的回答):

l <- list(list(col1="a",col2=1),list(col1="b",col2=2))
f = function(x) function(i) unlist(lapply(x, `[[`, i), use.names=FALSE)
as.data.frame(Map(f(l), names(l[[1]])))

这是最后对我有用的方法:

do.call(“rbind”, lapply(S1, as.data.frame))