在R语言中对体育数据框分组聚合生成球队排名表
高效生成足球联赛积分榜的R语言实现方案
原始数据
假设我们有如下R语言数据框df:
df <- data.frame( Home = c("Arsenal", "Chelsea", "Liverpool", "Chelsea", "Liverpool", "Arsenal"), Away = c("Chelsea", "Liverpool", "Arsenal", "Arsenal", "Chelsea", "Liverpool"), HomeGoals = c(3, 0, 2, 4, 3, 2), AwayGoals = c(1, 0, 1, 5, 2, 2), HomePoints = c(3, 1, 3, 0, 3, 1), AwayPoints = c(0, 1, 0, 3, 0, 1) )
需求说明
需要生成名为FinalStandings的新数据框,展示球队排名,排序优先级为总积分→净胜球→总进球(均按降序排列),最终数据需包含以下列:
Team:球队名称TotalPoints:总积分GoalDiff:净胜球(总进球数 - 总失球数)GoalsScored:总进球数
示例中Arsenal的对应行如下:
Team TotalPoints GoalDiff GoalsScored Arsenal 7 2 11
高效实现方案
无需拆分主客场分别汇总再合并,通过dplyr的长格式转换+分组聚合可以一次性完成计算,步骤如下:
library(dplyr) FinalStandings <- df %>% # 将每一行拆分为主场、客场两行数据,统一球队字段 tidyr::pivot_longer( cols = c(Home, Away), names_to = "Location", values_to = "Team" ) %>% # 根据主客场匹配对应的进球、积分和失球 mutate( Goals = case_when( Location == "Home" ~ HomeGoals, Location == "Away" ~ AwayGoals ), Points = case_when( Location == "Home" ~ HomePoints, Location == "Away" ~ AwayPoints ), GoalsConceded = case_when( Location == "Home" ~ AwayGoals, Location == "Away" ~ HomeGoals ) ) %>% # 按球队分组计算核心指标 group_by(Team) %>% summarise( TotalPoints = sum(Points), GoalsScored = sum(Goals), GoalDiff = sum(Goals - GoalsConceded), .groups = "drop" ) %>% # 按规则排序 arrange(desc(TotalPoints), desc(GoalDiff), desc(GoalsScored)) %>% # 调整列顺序为需求指定的格式 select(Team, TotalPoints, GoalDiff, GoalsScored)
结果验证
运行代码后,FinalStandings的输出结果如下:
# A tibble: 3 × 4 Team TotalPoints GoalDiff GoalsScored <chr> <dbl> <dbl> <dbl> 1 Arsenal 7 2 11 2 Liverpool 7 2 7 3 Chelsea 1 -4 7
结果完全符合需求:Arsenal的各项数据与示例一致,排序逻辑正确(Arsenal与Liverpool积分、净胜球相同,凭借更多总进球排名靠前)。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

