2017-05-05 75 views
0

我有以下列表:總和列相應於各行

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山坳,相對Var1行每個data.frame。

這裏我想要的輸出:

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

我怎樣才能做到這一點? Map在這種情況下有幫助嗎?

感謝

回答

3

使用do.callrbind列表的個人dataframes成一個單一的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 
+0

rbindlist你可以(通過=名單(VAR1 = VAR1),和cbind(頻率=頻率),))'和'骨料添加列名。 – lmo

3

另一個想法:

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 
2

另一個想法是從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