如何在R中按两列合并DataFrame并统计球队赛季预期进球数据?
解决方案:计算足球赛季预期进球差值
要实现目标,核心是先把每场比赛的对阵关系拆分为每个球队对应对手的记录,再分别关联自身和对手的预期进球数据,最后分组汇总。以下是完整的R代码实现:
步骤1:加载所需工具包
首先加载dplyr和tidyr用于数据处理:
library(dplyr) library(tidyr)
步骤2:转换对阵数据格式
将原有的match_opponents从宽格式转为长格式,为每个球队生成一条记录,并标注其对手:
team_matches <- match_opponents %>% pivot_longer(cols = c(home_team, away_team), names_to = "team_role", values_to = "team_name") %>% mutate(opponent = ifelse(team_role == "home_team", away_team, home_team)) %>% select(match_id, team_name, opponent)
步骤3:关联自身预期进球数据
通过match_id和team_name关联team_xG,得到每个球队每场的预期进球(即expected_goals_for):
team_xG_for <- team_matches %>% left_join(team_xG, by = c("match_id", "team_name")) %>% rename(expected_goals_for = expected_goals)
步骤4:关联对手预期进球数据
通过match_id和opponent关联team_xG,得到每个球队每场的预期失球(即expected_goals_against):
team_xG_against <- team_xG_for %>% left_join(team_xG, by = c("match_id", "opponent" = "team_name")) %>% rename(expected_goals_against = expected_goals)
步骤5:分组汇总赛季数据
按球队分组,求和得到赛季总预期进球和总预期失球:
xG_output <- team_xG_against %>% group_by(team_name) %>% summarise( expected_goals_for = sum(expected_goals_for), expected_goals_against = sum(expected_goals_against) ) %>% ungroup() # 输出结果 print(xG_output)
运行后得到的结果与你要求的xG_output完全一致:
# A tibble: 3 × 3 team_name expected_goals_for expected_goals_against <chr> <dbl> <dbl> 1 Team 1 2.5 4.5 2 Team 2 5.4 3.2 3 Team 3 4.3 4.5
内容的提问来源于stack exchange,提问作者Neal
相关产品推荐
相关产品推荐

