我有一个具有三个级别的嵌套列表。我需要取消列出中间级别,但我还没有找到一种简单的方法来做到这一点。
例如
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)
Run Code Online (Sandbox Code Playgroud)
我想要实现的是
newMasterList <- list(A = rbind(df1,df2), B = rbind(df3,df4))
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用两个递归选项 unlist() 但它们没有产生预期的结果:
newMasterListFAIL1 <- lapply(seq_along(masterList), function(x) unlist(masterList[[x]], recursive = F))
newMasterListFAIL2 <- lapply(seq_along(masterList), function(x) unlist(masterList[[x]]))
Run Code Online (Sandbox Code Playgroud)
您可以rbindlist
从data.table
包中快速尝试(但您的列表data.frame
将被转换为列表data.table
):
library(data.table)
newMasterList = lapply(masterList, rbindlist)
Run Code Online (Sandbox Code Playgroud)
来自@akrun 的基本 R 解决方案:
newMasterList = lapply(masterList, function(x) do.call(rbind, x))
Run Code Online (Sandbox Code Playgroud)
来自@David Arenburg 的优雅解决方案
library(tidyr)
newMasterList = lapply(masterList, unnest)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4020 次 |
最近记录: |