【发布时间】:2019-04-26 14:03:01
【问题描述】:
我有一个包含多个分类变量的数据集
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 对多个分类变量进行分组,以产生所需的输出?或者可能是 data.table?
【问题讨论】: