使用dplyr汇总R:2个不同列中的值

时间:2018-12-27 17:33:37

标签: r dplyr

我有以下数据框:

 points_team1 points_team2               team1                team2
------------------------------------------------------------------------
1           42           32       Doppler/Horst        Doherty/Allen
2           40           46   Abbiati/Andreatta          Mesa/Garcia
3           50           49      Bergmann/Harms        Basta/Kolaric
4           46           48     Mol H./Berntsen          Regza/Smits
5           29           42       Doppler/Horst        Hyden/Brunner
6           31           42       Hyden/Brunner   Liamin/Krasilnikov

现在,我想计算每支球队得分和输掉的总分。请注意,一个团队可能是第1团队或第2团队(例如Hyden / Brunner每边只有一次)。

我尝试使用gather,但后来陷入了如何使用SUMIF之类的问题。

k <- structure(list(points_team1 = c(42, 40, 50, 46, 29, 31), points_team2 = c(32, 
46, 49, 48, 42, 42), team1 = c("Doppler/Horst", "Abbiati/Andreatta", 
"Bergmann/Harms", "Mol H. / Berntsen", "Doppler/Horst", "Hyden/Brunner"
), team2 = c("Doherty/Allen", "Mesa/Garcia", "Basta/Kolaric", 
"Regza/Smits", "Hyden/Brunner", "Liamin/Krasilnikov")), row.names = c(NA, 
-6L), class = "data.frame")

v <- k %>% tidyr::gather('team1','team2', key="team_id", value="teamname") %>% 
                  dplyr::group_by(teamname) %>% 
                  dplyr::summarize(matches_played=n(), points_won=sum(points_team1[team_id == "team1"]))

给定数据集的预期结果将是:

teamname                points_won     points_lost
-----------------------------------------------------
1 Doppler/Horst         71             74
2 Abbiati/Andreatta     40             46
3 Mesa/Garcia           46             40
4 Hyden/Brunner         73             71
...

我从研究google和stackoverflow获得的结果仅给我答案,将包含某个元素的所有行加起来(例如:Summarize with conditions in dplyr),但在我的问题中,要加总的列可能取决于2个不同的列,我不知道该怎么做。

请帮助!

1 个答案:

答案 0 :(得分:2)

您可以建立两个数据框,每个团队一个,使用相同的名称,然后将它们堆叠在一起并像往常一样汇总。

team1 <- k %>% select(points_won = points_team1,
                      points_lost = points_team2,
                      team = team1)

team2 <- k %>% select(points_won = points_team2,
                      points_lost = points_team1,
                      team = team2)

bind_rows(team1, team2) %>%
    group_by(team) %>%
    summarise_all(sum)