R语言 根据列表的名称合并多个列表
问题描述
如何合并一个包含多个(“外部”)列表的列表,以使具有相同名称的(“内部”)列表对象合并在外部层中。
最好使用r-base(无需额外的库)。
请参见下方的示例数据和所需的输出结构。
# Outer list 1, with three inner lists
list_1 <- list(
layer_1 = list(A1 = c(1, 2, 3)),
layer_2 = list(A1 = c(1, 2, 3)),
layer_3 = list(A1 = c(1, 2, 3)))
# Outer list 2, with three inner lists
list_2 <- list(
layer_1 = list(B1 = c(4, 5, 6)),
layer_2 = list(B1 = c(4, 5, 6)),
layer_3 = list(B1 = c(4, 5, 6)))
# This works
list_1_2 <- list(list_1, list_2)
do.call("modifyList", list_1_2)
# Outer list 3, with three inner lists
list_3 <- list(
layer_1 = list(C1 = c(7, 8, 9)),
layer_2 = list(C1 = c(7, 8, 9)),
layer_3 = list(C1 = c(7, 8, 9)))
# This does not work
list_1_2_3 <- list(list_1, list_2, list_3)
do.call("modifyList", list_1_2_3)
# I have also tried using lapply
lapply(modifyList, list_1_2_3)
我想将list_1_2_3重组为如下格式:
# Wanted end result
end_list_1_2_3 <- list(
layer_1 = list(A1 = c(1, 2, 3), B1 = c(4, 5, 6), C1 = c(7, 8, 9)),
layer_2 = list(A1 = c(1, 2, 3), B1 = c(4, 5, 6), C1 = c(7, 8, 9)),
layer_3 = list(A1 = c(1, 2, 3), B1 = c(4, 5, 6), C1 = c(7, 8, 9)))
end_list_1_2_3
解决方案
Reduce
是你的朋友。
> res <- Reduce(modifyList, mget(ls(pattern='^list_\\d$')))
> all.equal(res, end_list_1_2_3)
[1] TRUE