【发布时间】:2020-02-17 00:00:13
【问题描述】:
我有一个数据集,其中包含分组做出的个人决定。对于每个人,我需要他/她的小组成员的所有决定的汇总(比如说总和)。 所以假设数据看起来像:
set.seed(123)
group_id <- c(sapply(seq(1, 3), rep, times = 3))
person_id <- rep(seq(1,3),3)
decision <- sample(1:10, 9, replace=T)
df <-data.frame(group_id, person_id, decision)
df
结果是:
group_id person_id decision
1 1 1 3
2 1 2 8
3 1 3 5
4 2 1 9
5 2 2 10
6 2 3 1
7 3 1 6
8 3 2 9
9 3 3 6
我需要制作类似的东西:
group_id person_id decision others_decision
1 1 1 3 13
2 1 2 8 8
3 1 3 5 11
因此,对于组中的每个元素,我让同一组的所有其他成员做某事(总和)。我可以只用一个for 循环来做到这一点,但它看起来丑陋且效率低下。有没有更好的解决方案?
更新:
这是我目前想出的解决方案,丑陋见谅:
df$other_decision=unlist(by(df, 1:nrow(df), function(row) {
df %>% filter(group_id==row$group_id, person_id!=row$person_id) %>% summarize(sum(decision))
}
))
df
【问题讨论】:
-
如果它“只是”一个
sum:df %>% group_by(group_id) %>% mutate(other = sum(decision) - decision)