如何在R嵌套列表中取消列出任意级别?

7

我有一个三级嵌套列表。我需要将中间层级的列表解构,但是我还没有找到一个简单的方法来实现。

例如:

df1 <- data.frame(X = sample(100),
                  Y = sample(100))
df2 <- data.frame(X = sample(50),
                  Y = sample(50))
df3 <- data.frame(X = sample(150),
                  Y = sample(150),
                  Z = sample(150)) 
df4 <- data.frame(X = sample(20),
                  Y = sample(20),
                  Z = sample(20))

list1 <- list(A = df1, B = df2)
list2 <- list(A = df3, B = df4)

masterList <- list(list1, list2)

What I want to achieve is

newMasterList <- list(A = rbind(df1,df2), B = rbind(df3,df4))

我尝试使用unlist()函数,但是无论使用哪个递归选项都不能得到期望的结果:

newMasterListFAIL1 <- lapply(seq_along(masterList), function(x) unlist(masterList[[x]], recursive = F))

newMasterListFAIL2 <- lapply(seq_along(masterList), function(x) unlist(masterList[[x]]))

3
请尝试使用 lapply(masterList, function(x) do.call(rbind, x))。该代码的作用为将 masterList 列表中的每个元素应用于 do.call(rbind, x) 函数,然后返回合并后的结果。 - akrun
2
更快的方法:lapply(masterList, rbindlist) 或者使用 data.table 包中的 rbindlist 函数。较慢的方法是:lapply(masterList, function(x) Reduce(rbind, x)) - Colonel Beauvel
谢谢你们俩!回答了我的问题。我需要更加熟悉 data.table,它似乎是一个很棒的包。 - Antti
1个回答

6

您可以尝试使用data.table包中的快速rbindlist函数(但您的data.frame列表将被转换为data.table列表):

library(data.table)

newMasterList = lapply(masterList, rbindlist)

来自@akrun的基本R解决方案:
newMasterList = lapply(masterList, function(x) do.call(rbind, x))

来自 @David Arenburg 的优雅解决方案

library(tidyr)

newMasterList = lapply(masterList, unnest)

3
如果你不想让别人抢了你的风头,我建议你加上lapply(masterList, unnest)。另外,你和@akrun都提出了这个解决方案,所以最好将其作为备选方案添加进去,因为看起来@akrun不打算发布它。请注意,翻译时不能改变原意。 - David Arenburg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接