R 如何删除行并用复杂条件替换值?
样本数据如下所示:R 如何删除行并用复杂条件替换值?,r,R,样本数据如下所示: > 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 过程是:对于每个年龄段,只保留一行math>5的数据,用总和替换总和 对于第1行,math=4,而
> 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
过程是:对于每个年龄段,只保留一行math>5的数据,用总和替换总和
对于第1行,math=4,而不是>5,则保留该行。
对于第2行,
math=6,>5,然后寻找另一个年龄与16岁和16岁相同的行
数学>5,即第5行。然后7+3=10,将第2行的总数替换为
10,并删除第5行。
对于第3行,唯一的匹配年龄是第1行,但是
第15行的数学,但18岁时不匹配,则保留这一行。
预期结果如下:
age math total
1 13 4 5
2 16 7 10
3 13 8 6
4 18 6 5
如何做?使用dplyr,我们可以将问题分为两部分。对于第一部分,我们过滤math>5的行,按年龄分组,取math的第一个值和总和,并绑定math感谢您的好答案的行!请你看看另一个难题:
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