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

下面是一些示例数据:

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

当前回答

如果您的列表具有相同尺寸的元素,则可以使用来自tidyverse的bind_rows函数。

# Load the tidyverse
Library(tidyverse)

# make a list with elements having same dimensions
My_list <- list(a = c(1, 4, 5), b = c(9, 3, 8))

## Bind the rows
My_list %>% bind_rows()

结果是一个有两行的数据帧。

其他回答

用rbind

do.call(rbind.data.frame, your_list)

编辑:以前的版本返回list的data.frame而不是向量(正如@IanSudbery在评论中指出的那样)。

l <- replicate(10,list(sample(letters, 20)))
a <-lapply(l[1:10],data.frame)
do.call("cbind", a)

扩展@Marek的回答:如果你想避免字符串变成因素和效率不是一个问题,尝试一下

do.call(rbind, lapply(your_list, data.frame, stringsAsFactors=FALSE))

对于使用purrr系列解决方案的并行(多核,多会话等)解决方案,使用:

library (furrr)
plan(multisession) # see below to see which other plan() is the more efficient
myTibble <- future_map_dfc(l, ~.x)

其中l是列表。

要对最有效的计划()进行基准测试,您可以使用:

library(tictoc)
plan(sequential) # reference time
# plan(multisession) # benchamark plan() goes here. See ?plan().
tic()
myTibble <- future_map_dfc(l, ~.x)
toc()

2020年7月更新:

stringsAsFactors参数的默认值现在是default.stringsAsFactors(),它的默认值是FALSE。


假设你的列表的列表叫做l:

df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE))

上面的代码会将所有的字符列转换为因子,为了避免这种情况,你可以在data.frame()调用中添加一个参数:

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