如何使用 tidyverse 函数将一列的变量与其他列的数值相加

How to use tidyverse functions to sum up variables of one column with numeric values of others

一个非常初学者的问题...我有一个足球队 20 多个赛季的联赛表现的虚构练习数据集,设置如下:

Brighton <- tribble(
  ~"Year", ~"League", ~"Win", ~"Draw", ~"Lose", ~"Points", ~"Position",
  # -------------------------------------------------------------------
  2021, "Premier", 10, 0, 28, 30, 19,
  2022, "Championship", 27, 0, 19, 81, 3,
  2023, "Championship", 20, 5, 21, 65, 7,
  2024, "Championship", 15, 9, 22, 54, 12,
  2025, "Championship", 20, 8, 18, 68, 6,
  2026, "Premier", 16, 5, 17, 53, 11,
  2027, "Premier", 10, 5, 23, 35, 18,
  2028, "Championship", 25, 5, 16, 80, 2,
  2029, "Premier", 18, 5, 15, 59, 7,
  2030, "Premier", 21, 3, 14, 66, 5,
  2031, "Premier", 16, 8, 14, 56, 10,
  2032, "Premier", 15, 7, 14, 52, 12,
  2033, "Premier", 15, 1, 22, 46, 15,
  2034, "Premier", 11, 7, 20, 40, 17,
  2035, "Premier", 18, 2, 18, 56, 10,
  2036, "Premier", 11, 3, 24, 36, 18,
  2037, "Championship", 23, 7, 16, 76, 3,
  2038, "Championship", 21, 8, 17, 71, 4,
  2039, "Championship", 12, 10, 24, 46, 22,
  2040, "League One", 18, 6, 22, 60, 8,
  2041, "League One", 15, 8, 23, 53, 10
)

Brighton$Year <- as.integer(Brighton$Year)

我想做的是总结每个“联赛”变量(英超、冠军、联赛)的总比赛数,所有获胜、失败和平局。

我已经能够在如下情节中做到这一点:

Br_long <- Brighton %>%
  pivot_longer(c("Win", "Draw", "Lose"), values_to = "Games")

ggplot(Br_long) +
         geom_col(mapping = aes(x = League, 
                                y = Games), 
                  position = "stack"
)

但我无法实际计算出总游戏数(以便将输出包含在 rmd 内联代码中)。

我的问题:我使用什么 tidyverse (tidyr, dplyr) 代码来将数据集中进行的所有英超比赛、冠军比赛和联赛一级比赛相加(无论是赢、输还是平),这样我就得到了三个总数?

我希望我能向您展示我尝试过的事情,但我尝试了很多不同的事情,看了很多教程,阅读了很多在线文档,但我迷路了。

我将不胜感激任何对我的解决方案的帮助,或者将我送往何处以及如何学习做好这件事。谢谢!

dplyr 的 across,在 dplyr 1.0.0 中添加,对此很有用:

Brighton %>%
  group_by(League) %>%
  summarize(across(Win:Lose, sum))

 A tibble: 3 x 4
  League         Win  Draw  Lose
  <chr>        <dbl> <dbl> <dbl>
1 Championship   163    52   153
2 League One      33    14    45
3 Premier        161    46   209

如果你需要得到所有游戏的总和,所以最终得到 3 个总数,这就是答案:

Brighton %>% 
 group_by(League) %>% 
 summarise(Games = sum(Win, Draw, Lose))

#> # A tibble: 3 x 2
#>   League       Games
#>   <chr>        <dbl>
#> 1 Championship   368
#> 2 League One      92
#> 3 Premier        416

如果您需要分别计算输赢和平局的总和,那么您正在寻找的答案是@Jon 的。