使用dplyr来计算多个分组依据变量

时间:2018-11-24 05:37:35

标签: r group-by count dplyr

我有一个包含多个类别变量的数据集

data <- data_frame(
HomeTeam = c("Team1", "Team2", "Team3", "Team4", "Team2", "Team2", "Team4", 
             "Team3", "Team2", "Team1", "Team3", "Team2"),
AwayTeam = c("Team2", "Team1", "Team4", "Team3", "Team1", "Team4", "Team1", 
             "Team2", "Team3", "Team3", "Team4", "Team1"),
HomeScore = c(10, 5, 12, 18, 17, 19, 23, 17, 34, 19, 8, 3),
AwayScore = c(4, 16, 9, 19, 16, 4, 8, 21, 6, 5, 9, 17),
Venue = c("Ground1", "Ground2", "Ground3", "Ground3", "Ground1", "Ground2", 
          "Ground1", "Ground3", "Ground2", "Ground3", "Ground4", "Ground2"))

我基本上想通过计数将“ HomeTeam”和“ AwayTeam”汇总到一个新表中,如下所示

 HomeTeam NumberOfGamesHome NumberOfGamesaWAY
 <chr>                <int>             <int>
 1 Team1                    2                 4
 2 Team2                    5                 2
 3 Team3                    3                 3
 4 Team4                    2                 3

我当前的方法需要两行分组代码,然后将表连接起来

HomeTeamCount <- data %>% 
group_by(HomeTeam) %>% 
summarise(NumberOfGamesHome = n()) 

AwayTeamCount <- data %>% 
group_by(AwayTeam) %>% 
summarise(NumberOfGamesAway = n()) 

Desired <- left_join(HomeTeamCount, AwayTeamCount, 
                 by = c("HomeTeam" = "AwayTeam"))

在我的实际数据集中,我有大量的分类变量,采用上述方法似乎很费力且效率低

dplyr是否有办法通过多个类别变量对group_by产生所需的输出?还是潜在的data.table?

我已经咨询了其他几个问题,例如herehere,但是无法找出答案。

1 个答案:

答案 0 :(得分:3)

这里有一种可能性,可以使用gather将数据从宽范围传播到长范围,按团队分组并汇总主场和客场比赛的次数。

library(tidyverse)
data %>%
    gather(key, Team) %>%
    group_by(Team) %>%
    summarise(
        NumberOfGamesHome = sum(key == "HomeTeam"),
        NumberOfGamesaWAY = sum(key == "AwayTeam"))
## A tibble: 4 x 3
#  Team  NumberOfGamesHome NumberOfGamesaWAY
#  <chr>             <int>             <int>
#1 Team1                 2                 4
#2 Team2                 5                 2
#3 Team3                 3                 3
#4 Team4                 2                 3

更新

要用其他列反映更新后的样本数据

data %>%
    gather(key, Team, HomeTeam, AwayTeam) %>%
    group_by(Team) %>%
    summarise(
        NumberOfGamesHome = sum(key == "HomeTeam"),
        NumberOfGamesaWAY = sum(key == "AwayTeam"))
## A tibble: 4 x 3
#  Team  NumberOfGamesHome NumberOfGamesaWAY
#  <chr>             <int>             <int>
#1 Team1                 2                 4
#2 Team2                 5                 2
#3 Team3                 3                 3
#4 Team4                 2                 3