汇总dplyr中每组的所有其他值

Phi*_*ski 7 r dplyr

我有一个数据集,其中有成组的个人决策。对于每个人,我需要他/她的小组成员的所有决定的汇总(即总和)。所以说数据看起来像:

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
Run Code Online (Sandbox Code Playgroud)

结果是:

  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
Run Code Online (Sandbox Code Playgroud)

我需要产生这样的东西:

  group_id person_id decision others_decision
1        1         1        3 13
2        1         2        8  8
3        1         3        5 11
Run Code Online (Sandbox Code Playgroud)

因此,对于组中的每个元素,我都得到了同一组中的所有其他成员,并做了一些事(求和)。我可以通过一个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
Run Code Online (Sandbox Code Playgroud)

tmf*_*mnk 4

你可以做:

df %>%
 inner_join(df, by = c("group_id" = "group_id")) %>%
 filter(person_id.x != person_id.y) %>%
 group_by(group_id, person_id = person_id.x) %>%
 summarise(decision = first(decision.x),
           others_decison = sum(decision.y))

  group_id person_id decision others_decison
     <int>     <int>    <int>          <int>
1        1         1        3             13
2        1         2        8              8
3        1         3        5             11
4        2         1        9             11
5        2         2       10             10
6        2         3        1             19
7        3         1        6             15
8        3         2        9             12
9        3         3        6             15
Run Code Online (Sandbox Code Playgroud)

根据您的实际数据集(其大小),它可能会在计算上变得相当要求,因为它涉及内部联接。

另一种不涉及内连接的可能性是:

df %>% 
 group_by(group_id) %>% 
 mutate(others_decison = list(decision),
        rowid = 1:n()) %>%
 ungroup() %>%
 rowwise() %>%
 mutate(others_decison = sum(unlist(others_decison)[-rowid])) %>%
 ungroup() %>%
 select(-rowid)
Run Code Online (Sandbox Code Playgroud)