汇总团队成员的平均分数

时间:2019-01-25 05:35:40

标签: r aggregate mean

我有团队成员的数据。每个团队大约有5名成员。典型的集合函数将使我能够计算出整个团队的平均得分。但是,我有兴趣为每个参与者计算除参与者得分以外的参与者团队成员的平均分数。关于如何做到这一点的任何建议?

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则可以尝试以下操作:

library(dplyr)

df <- tibble(team = c(rep("A", 5), rep("B", 5), rep("C", 5)),
             player = letters[1:15],
             score = 1:15)

# find aggregate team scores and number of team members
team_means <- df %>%
  group_by(team) %>%
  summarise(team_sum = sum(score, na.rm = TRUE),
            team_n = n())

# find average of rest of team's performance
# this is the the "remaining players' average"; the "- 1" could be removed for the team average.
left_join(df, team_means, by = "team") %>%
  mutate(average = (team_sum - score) / (team_n - 1)) %>%
  select(team, player, score, average)

# A tibble: 15 x 4
   team  player score average
   <chr> <chr>  <int>   <dbl>
 1 A     a          1    3.5 
 2 A     b          2    3.25
 3 A     c          3    3   
 4 A     d          4    2.75
 5 A     e          5    2.5 
 6 B     f          6    8.5 
 7 B     g          7    8.25
 8 B     h          8    8   
 9 B     i          9    7.75
10 B     j         10    7.5 
11 C     k         11   13.5 
12 C     l         12   13.2 
13 C     m         13   13   
14 C     n         14   12.8 
15 C     o         15   12.5