如何使用dplyr来总结不符合组的值 [英] How to summarize value not matching the group using dplyr
本文介绍了如何使用dplyr来总结不符合组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对属于该行组以外的组的行进行求和。例如使用此样本数据
I want to sum values of rows which belongs to group other than the row's group. For example using this sample data
> df <- data.frame(id=1:5, group=c("A", "A", "B", "B", "A"), val=seq(9, 1, -2))
> df
id group val
1 1 A 9
2 2 A 7
3 3 B 5
4 4 B 3
5 5 A 1
按 dplyr
按小组汇总
> df %>% group_by(group) %>% summarize(sumval = sum(val))
Source: local data frame [2 x 2]
group sumval
(fctr) (dbl)
1 A 17
2 B 8
什么我想要的是属于组A的行的值使用不是组A的 sumval
。最终结果是
What I want is the value for rows belonging to group A to use sumval
of not group A. i.e. the final result is
id group val notval
1 1 A 9 8
2 2 A 7 8
3 3 B 5 17
4 4 B 3 17
5 5 A 1 8
有没有办法在 dplyr
?最重要的是在单链中?
Is there a way to do this in dplyr
? Preferrably in a single chain?
推荐答案
@akrun答案是最好的。但是,如果你想在 dplyr
中做,这是一个圆滑的方式。
@akrun answers are best. But if you want to do in dplyr
, this is a round about way.
df <- data.frame(id=1:5, group=c("A", "A", "B", "B", "A"), val=seq(9, 1, -2))
df %>% mutate(TotalSum = sum(val)) %>% group_by(group) %>%
mutate(valsumval = TotalSum - sum(val))
Source: local data frame [5 x 5]
Groups: group [2]
id group val TotalSum valsumval
(int) (fctr) (dbl) (dbl) (dbl)
1 1 A 9 25 8
2 2 A 7 25 8
3 3 B 5 25 17
4 4 B 3 25 17
5 5 A 1 25 8
即使有两个以上的组也是如此。
This also works even if there are more than two groups.
另外这个工作
df %>% group_by(group) %>% mutate(notval = sum(df$val)- sum(val))
这篇关于如何使用dplyr来总结不符合组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文