我有一个嵌套的数据列表。它的长度是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]])))

其他回答

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

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

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

如何使用map_函数和一个for循环?以下是我的解决方案:

list_to_df <- function(list_to_convert) {
  tmp_data_frame <- data.frame()
  for (i in 1:length(list_to_convert)) {
    tmp <- map_dfr(list_to_convert[[i]], data.frame)
    tmp_data_frame <- rbind(tmp_data_frame, tmp)
  }
  return(tmp_data_frame)
}

其中map_dfr将每个列表元素转换为data.frame,然后rbind将它们合并。

在你的情况下,我猜应该是:

converted_list <- list_to_df(l)

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)

对于使用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()