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

编写worldfootballR函数简化多国家多赛季转会身价统计脚本

批量处理多国多赛季球员身价数据的自定义函数

针对你需要处理大量国家和赛季数据的需求,下面是封装好的R函数,基于worldfootballR和dplyr实现,能一次性生成包含球队总身价、防守位置分位置身价及总防守身价的整合结果。

library(worldfootballR)
library(dplyr)
library(purrr)

# 自定义批量处理函数
get_team_valuations <- function(country_names, start_years) {
  # 生成所有国家-赛季的组合
  country_season_combinations <- cross_df(list(
    country = country_names,
    season = start_years
  ))
  
  # 遍历每个组合,抓取并处理数据
  country_season_combinations %>%
    mutate(data = map2(country, season, function(cntry, yr) {
      # 抓取该国家该赛季的球员身价数据
      player_data <- tm_player_market_values(country_name = cntry, start_year = yr)
      
      # 计算球队总身价
      team_total_val <- player_data %>%
        group_by(squad) %>%
        summarise(tot_val = sum(player_market_value_euro, na.rm = TRUE), .groups = "drop")
      
      # 计算防守位置各位置及总防守身价
      team_def_val <- player_data %>%
        group_by(squad) %>%
        summarise(
          tot_cb = sum(player_market_value_euro[player_position == "Centre-Back"], na.rm = TRUE),
          tot_lb = sum(player_market_value_euro[player_position == "Left-Back"], na.rm = TRUE),
          tot_rb = sum(player_market_value_euro[player_position == "Right-Back"], na.rm = TRUE),
          .groups = "drop"
        ) %>%
        mutate(tot_def = tot_cb + tot_lb + tot_rb)
      
      # 合并总身价和防守身价数据
      left_join(team_total_val, team_def_val, by = "squad") %>%
        mutate(country = cntry, season = yr)
    })) %>%
    # 展开所有结果为单个数据框
    unnest(data) %>%
    # 调整列顺序,让标识列在前
    select(country, season, squad, tot_val, tot_cb, tot_lb, tot_rb, tot_def)
}

使用示例

# 定义要处理的国家和赛季
target_countries <- c("England", "Spain", "Germany")
target_seasons <- 2020:2025

# 运行函数获取结果
all_team_vals <- get_team_valuations(target_countries, target_seasons)

# 查看结果
head(all_team_vals)

关键说明

  • 函数自动遍历所有国家-赛季组合,无需重复编写单赛季单国家的冗余代码
  • 用unnest将嵌套数据展开为标准长格式,便于后续分析或可视化
  • 新增country和season标识列,清晰区分不同数据集
  • 改用mutate计算总防守身价tot_def,比原代码的cbind更符合tidyverse规范,避免列数不匹配风险
  • 若需扩展其他位置统计,只需在team_def_val的summarise块中添加对应位置的求和逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:52:21