r - 计算 group_by 中行之间的差异分数
问题描述
我正在处理一些比赛数据,并想计算出每支球队在每场比赛中的目标差异。
我可以得到二队的分差(在 diff 列中),但我不知道如何计算一队的净胜球。它应该是第二支球队的目标差异的倒数(即在样本数据集中,“咆哮者”应该1
在差异列中,“罢工”应该有-1
)。
library(dplyr)
dat <-
structure(
list(
Match = c(1, 1, 2, 2, 3, 3),
Team = c("Growlers",
"Rollers", "Strike", "Bandits", "Cats", "Blues"),
Goals = c(1,0, 0, 1, 1, 2)
),
row.names = c(NA,-6L),
groups = structure(
list(
Match = c(895825, 895826, 895827),
.rows = list(1:2, 3:4,
5:6)
),
row.names = c(NA,-3L),
class = c("tbl_df", "tbl",
"data.frame"),
.drop = TRUE
),
class = c("grouped_df", "tbl_df",
"tbl", "data.frame")
)
dat %>%
group_by(Match) %>%
mutate(diff = Goals - lag(Goals))
#> # A tibble: 6 x 4
#> # Groups: Match [3]
#> Match Team Goals diff
#> <dbl> <chr> <dbl> <dbl>
#> 1 1 Growlers 1 NA
#> 2 1 Rollers 0 -1
#> 3 2 Strike 0 NA
#> 4 2 Bandits 1 1
#> 5 3 Cats 1 NA
#> 6 3 Blues 2 1
由reprex 包(v0.2.0)于 2019 年 2 月 26 日创建。
解决方案
一种快速而肮脏的方法是明确计算团队 1 和团队 2 的分数,如下所示:
dat %>%
group_by(Match) %>%
mutate(
diff = c(
Goals[1] - Goals[2],
Goals[2] - Goals[1]
)
)
#> # A tibble: 6 x 4
#> # Groups: Match [3]
#> Match Team Goals diff
#> <dbl> <chr> <dbl> <dbl>
#> 1 1 Growlers 1 1
#> 2 1 Rollers 0 -1
#> 3 2 Strike 0 -1
#> 4 2 Bandits 1 1
推荐阅读
- r - R data.table:如何引用链中的当前对象?
- python - Python:从另一个模块访问全局字典
- python - 如何让我公司的法律部门相信 Python 密码学模块只是一个包装器?
- javascript - 使用谷歌脚本发送电子邮件多个超链接
- javascript - 无法让它停止滚动到网页底部
- google-apps-script - 如何使用不断增长的 Google 表格使用自定义 UI 按钮正确调用函数?
- gradle - 为什么我无法从包 com.google.protobuf.util 导入 JsonFormat?
- java - 从 Java 程序中读取 Kube Secrets
- node.js - Angular不支持当前版本的Node(16.4.1)。如何完全摆脱mac中的软件?
- javascript - 如何为自定义 mongoose SchemaType 的所有实例提供默认验证?