You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中如何基于已有数据框为新数据框添加胜负平战绩列

R语言实现球队战绩统计

步骤1:构建原始数据

先把你给出的比赛数据和球队数据转换成R的数据框:

# 原始比赛数据
match_data <- data.frame(
  HomeTeam = c("Liverpool", "Brighton", "Birmingham", "Manchester", "Portsmouth"),
  AwayTeam = c("Netherland", "Austria", "Cambodia", "Netherlands", "Austria"),
  Results = c("H", "H", "P", "D", "H"),
  stringsAsFactors = FALSE
)

# 你已创建的球队列表
teams <- data.frame(
  TeamName = c("Liverpool", "Brighton", "Birmingham", "Manchester", "Netherland", "Austria", "Cambodia", "Portsmouth"),
  stringsAsFactors = FALSE
)

步骤2:加载工具包(如果未安装先安装)

我们用dplyr包来简化数据处理,新手更容易理解:

# 首次使用先安装
install.packages("dplyr")
# 加载包
library(dplyr)

步骤3:统计每队的胜/负/平次数

把每场比赛的主客队战绩拆分,再合并统计:

# 处理主队的战绩记录
home_records <- match_data %>%
  mutate(
    Team = HomeTeam,
    Win = ifelse(Results == "H", 1, 0),  # H代表主队胜
    Loss = ifelse(Results == "P", 1, 0), # P代表客队胜,即主队负
    Draw = ifelse(Results == "D", 1, 0)  # D代表平局
  ) %>%
  select(Team, Win, Loss, Draw)

# 处理客队的战绩记录
away_records <- match_data %>%
  mutate(
    Team = AwayTeam,
    Win = ifelse(Results == "P", 1, 0),  # P代表客队胜
    Loss = ifelse(Results == "H", 1, 0), # H代表主队胜,即客队负
    Draw = ifelse(Results == "D", 1, 0)  # D代表平局
  ) %>%
  select(Team, Win, Loss, Draw)

# 合并所有记录,按球队分组求和
all_records <- bind_rows(home_records, away_records) %>%
  group_by(Team) %>%
  summarise(
    Win = sum(Win),
    Loss = sum(Loss),
    Draw = sum(Draw),
    .groups = "drop"
  )

步骤4:合并战绩到球队数据框并生成Record列

把统计好的战绩合并到你已有的球队列表,再拼接成「胜-负-平」的格式:

teams <- teams %>%
  left_join(all_records, by = c("TeamName" = "Team")) %>%
  mutate(
    Record = paste0(Win, "-", Loss, "-", Draw)
  ) %>%
  select(TeamName, Record) # 只保留需要的列

# 查看结果
print(teams)

最终结果示例

运行后你会得到这样的输出:

TeamName Record
1    Liverpool   1-0-0
2     Brighton   1-0-0
3   Birmingham   0-1-0
4   Manchester   0-0-1
5   Netherland   0-1-0
6      Austria   0-2-0
7     Cambodia   1-0-0
8   Portsmouth   1-0-0

内容的提问来源于stack exchange,提问作者IAwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:20:29