样本数据如下:
> data.frame(age = c(13, 16, 13,18,16),math = c(4, 7, 8,6,6),total = c(5, 3, 6,5,7))
age math total
1 13 4 5
2 16 7 3
3 13 8 6
4 18 6 5
5 16 6 7
过程是:对于 each age
,只保留math
>5 的一行,用total
sum替换total
。
math
=4,而不是 >5,则保留该行。math
=6,>5,然后寻找具有相同age
16 和math
>5 的另一行,即第 5 行。然后 (7+3)=10,将total
第 2 行替换为10
,并删除第 5 行。age
是第 1 行,但math
第 1 行 <5,然后保持第 3 行相同。math
>5,但没有匹配age
18,则保留该行。预期结果如下:
age math total
1 13 4 5
2 16 7 10
3 13 8 6
4 18 6 5
怎么做?
使用dplyr
,我们可以将问题分为两部分。对于第一部分,我们filter
where math > 5
,group_by
age
并获取和of 的first
值并绑定行 where 。math
sum
total
math <= 5
library(dplyr)
df %>%
filter(math > 5) %>%
group_by(age) %>%
summarise(math = first(math),
total = sum(total)) %>%
bind_rows(df %>% filter(math <= 5))
# age math total
# <dbl> <dbl> <dbl>
#1 13 8 6
#2 16 7 10
#3 18 6 5
#4 13 4 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句