【问题标题】:How to unlist an arbitrary level in R nested list?如何在 R 嵌套列表中取消列出任意级别?
【发布时间】:2015-08-06 21:18:02
【问题描述】:

我有一个包含三个级别的嵌套列表。我需要取消列出中间级别,但我还没有找到简单的方法。

例如

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)

我想要实现的是

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]]))

【问题讨论】:

  • 试试lapply(masterList, function(x) do.call(rbind, x))
  • 更快 ;) 较慢的方法:lapply(masterList, function(x) Reduce(rbind, x)) 或使用来自data.table 包的rbindlist 有效:lapply(masterList, rbindlist)
  • 谢谢你们!回答了我的问题。我需要更熟悉 data.table。这似乎是一个很棒的包。

标签: r dataframe


【解决方案1】:

您可以从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)

【讨论】:

  • 如果您不希望有人在这里窃取您的名声,我也会添加lapply(masterList, unnest)。此外,可能应该添加@akrun 评论作为基本替代品,因为你们俩自己想出了它,而且似乎 arkun 不会发布它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多