Reputation: 183
I have got the following list:
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)
I need to sum each Freq
col with the relative Var1
row for each data.frame.
Here my desired output:
Var1 Freq
1 45
2 31
3 25
5 101
6 92
7 19
9 17
11 76
15 6
20 54
How can I do this? Does Map
help in this case?
Thanks
Upvotes: 1
Views: 148
Reputation: 887501
Another idea is rbindlist
from 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
Upvotes: 2
Reputation: 21641
Another idea:
library(dplyr)
bind_rows(lst) %>% group_by(Var1) %>% summarise(Freq = sum(Freq))
Which gives:
## 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
Upvotes: 4
Reputation: 32548
Use do.call
to rbind
the individual dataframes of the list into a single data.frame and then use aggregate
to sum
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
Upvotes: 3