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

时间:2019-08-07 11:57:30

标签: r mapply

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

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将它们视为对象。但是我不知道该怎么做(如果可能的话)。我为此进行了整洁的评估,但我不知道这是否是这样做的方法。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以使用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")))