根据各自的行对列表中数据帧之间的列求和

Sum columns between dataframes in list accordingly to respective rows

我得到了以下列表:

df = read.table(text = 'Var1 Freq
1 12
2 19
3 3
5 7
6 55
9 17', header = TRUE)

df1 = read.table(text = 'Var1 Freq
1 16
2 1
3 22
5 87
6 5
7 9
11 76', header = TRUE)

df2 = read.table(text = 'Var1 Freq
1 17
2 11
5 7
6 32
7 10
15 6
20 54', header = TRUE)

lst = list(df, df1, df2)

我需要将每个 Freq 列与每个 data.frame 的相对 Var1 行相加。

这是我想要的输出:

Var1 Freq
1 45
2 31
3 25
5 101
6 92
7 19
9 17
11 76
15 6
20 54

我该怎么做? Map 对这种情况有帮助吗?

谢谢

使用do.call将列表的各个数据帧rbind合并为一个data.frame,然后使用aggregatesum

with(do.call(rbind, lst), aggregate(Freq, by = list(Var1), sum))
#   Group.1   x
#1        1  45
#2        2  31
#3        3  25
#4        5 101
#5        6  92
#6        7  19
#7        9  17
#8       11  76
#9       15   6
#10      20  54

另一个想法:

library(dplyr) 
bind_rows(lst) %>% group_by(Var1) %>% summarise(Freq = sum(Freq))

给出:

## A tibble: 10 × 2
#    Var1  Freq
#   <int> <int>
#1      1    45
#2      2    31
#3      3    25
#4      5   101
#5      6    92
#6      7    19
#7      9    17
#8     11    76
#9     15     6
#10    20    54

另一个想法是 rbindlist 来自 data.table

library(data.table)
rbindlist(lst)[, .(Freq = sum(Freq)), Var1]
#    Var1 Freq
# 1:    1   45
# 2:    2   31
# 3:    3   25
# 4:    5  101
# 5:    6   92
# 6:    9   17
# 7:    7   19
# 8:   11   76
# 9:   15    6
#10:   20   54