合并包含具有相同结构的列表的列表

Merge List containing Lists with the same structure

我有一个列表,其中包含多个具有相同结构的列表:

ls <- list(
one = list(df = data.frame(var1_1 = c(1, 1, 1),
                           var1_2 = c('a', 'a', 'a')),
           ls = list(n_df_1 = data.frame(var3_1 = c('x', 'x', 'x'),
                                         var3_2 = c(4, 4, 4))),
           name = c("one", "one", "one")),
two = list(df = data.frame(var1_1 = c(1, 1, 1),
                           var1_2 = c('a', 'a', 'a')),
           ls = list(n_df_1 = data.frame(var3_1 = c('x', 'x', 'x'),
                                         var3_2 = c(4, 4, 4))),
           name = c("two", "two", "two")))

我想合并所有这些嵌套列表,如下所述:Merge Two Lists in R

如果我这样做,它完全符合我的要求:

merged <- mapply(c, ls[[1]], ls[[2]], SIMPLIFY = FALSE)

问题是,主列表 (ls) 并不总是只有两个嵌套列表。我怎样才能使这段代码更加模块化?

我试图制作一个包含嵌套列表的所有索引的向量:

sapply(seq_along(ls), function(x) paste0("ls[[", x, "]]"))

哪个输出这个:

[1] "ls[[1]]" "ls[[2]]"

我想我可以取消引用这些字符向量,以便 R 将它们视为对象。但我不知道该怎么做(如果可能的话)。我为此查看了 tidy eval,但我不知道这是否是实现它的方法。

有什么建议吗?

您可以使用 Reduce 对抽象数量的列表元素执行此操作,即

Reduce(function(...)Map(c, ...), l1) #Map = mapply(..., simplify = FALSE)

这给出了,

$df
$df$var1_1
[1] 1 1 1

$df$var1_2
[1] a a a
Levels: a

$df$var1_1
[1] 1 1 1

$df$var1_2
[1] a a a
Levels: a


$ls
$ls$n_df_1
  var3_1 var3_2
1      x      4
2      x      4
3      x      4

$ls$n_df_1
  var3_1 var3_2
1      x      4
2      x      4
3      x      4


$name
[1] "one" "one" "one" "two" "two" "two"

数据:

dput(l1)
list(one = list(df = structure(list(var1_1 = c(1, 1, 1), var1_2 = structure(c(1L, 
1L, 1L), .Label = "a", class = "factor")), class = "data.frame", row.names = c(NA, 
-3L)), ls = list(n_df_1 = structure(list(var3_1 = structure(c(1L, 
1L, 1L), .Label = "x", class = "factor"), var3_2 = c(4, 4, 4)), class = "data.frame", row.names = c(NA, 
-3L))), name = c("one", "one", "one")), two = list(df = structure(list(
    var1_1 = c(1, 1, 1), var1_2 = structure(c(1L, 1L, 1L), .Label = "a", class = "factor")), class = "data.frame", row.names = c(NA, 
-3L)), ls = list(n_df_1 = structure(list(var3_1 = structure(c(1L, 
1L, 1L), .Label = "x", class = "factor"), var3_2 = c(4, 4, 4)), class = "data.frame", row.names = c(NA, 
-3L))), name = c("two", "two", "two")))