如何对列表中具有相同名称的数据框求和?

How to sum the data frames in a list that have the same name?

我有两个包含多个数据框的列表:

list_1 <- list(a = tibble(c(1,2),c(3,4)),
               b = tibble(c(3,4),c(2,5)),
               c = tibble(c(5,62),c(1,6)))

list_2 <- list(a = tibble(c(1,2),c(3,4)),
               b = tibble(c(3,4),c(2,5)),
               d = tibble(c(5,62),c(1,6)))

现在,我想总结所有具有相同名称的数据框。因此,所需的输出应如下所示:

list_1 <- list(a = tibble(c(2,4),c(6,8)),
               b = tibble(c(6,8),c(4,10)))

有没有人知道如何解决这个问题?

提前致谢。

您可以使用 intersect 获取两个列表中的常用名称,并使用 Map.

仅添加常用名称的两个列表
common_names <- intersect(names(list_1), names(list_2))
Map(`+`, list_1[common_names],  list_2[common_names])

#$a
#  c(1, 2) c(3, 4)
#1       2       6
#2       4       8

#$b
#  c(3, 4) c(2, 5)
#1       6       4
#2       8      10

purrrmap2相同:

purrr::map2(list_1[common_names],  list_2[common_names], `+`)