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

使用Lahman与baseballr时setnames()报错:列名与列数不匹配

解决statcast_search_pitchers列名不匹配错误

这个错误是因为baseballr包预设的列名数量与MLB Statcast API实际返回的字段数量不匹配,通常出现在R/RStudio更新后,旧版本包与新环境或API变更不兼容。以下是具体解决步骤:

1. 升级所有相关包到最新版本

这是最直接的解决方案,baseballr维护者会及时更新包以适配Statcast API的字段变化:

  • 先升级CRAN上的包:
    update.packages(c("baseballr", "data.table", "tidyverse", "dplyr", "Lahman"), ask = FALSE)
    
  • 如果CRAN版本仍未修复问题,直接从GitHub安装baseballr的开发版(需先安装devtools):
    install.packages("devtools")
    devtools::install_github("BillPetti/baseballr")
    

2. 手动获取并处理原始数据

若升级包后问题仍存在,可绕过baseballr的封装函数,直接调用Statcast API获取数据:

# Gerrit Cole的MLB选手ID是592450,2023赛季时间范围可根据实际调整
library(httr)
library(readr)

# 发送API请求获取原始CSV数据
raw_response <- GET(
  url = "https://baseballsavant.mlb.com/statcast_search/csv",
  query = list(
    player_id = 592450,
    game_date_gt = "2023-03-30",
    game_date_lt = "2023-10-01",
    player_type = "pitcher",
    type = "details"
  )
)

# 解析数据为data.frame
cole_2023_data <- read_csv(content(raw_response, "text"))

# 按需筛选列(示例,可根据需求调整)
library(dplyr)
cleaned_data <- cole_2023_data %>%
  select(pitch_type, release_speed, strike_zone_top, strike_zone_bottom, events)

3. 临时适配列名(不推荐)

如果不想重新安装包,可临时修改statcast_search_pitchers函数中的列名赋值逻辑,让它自动匹配存在的列:

# 先复制原函数代码并修改
statcast_search_pitchers_fixed <- function(start_date, end_date, pitcherid) {
  # 保留原函数的请求逻辑,仅修改setnames部分
  # ...(原函数其他代码)
  # 替换原setnames行:
  col_names <- c(/* 原函数中的列名向量 */)
  setnames(x, intersect(colnames(x), col_names))
  # ...(原函数剩余代码)
}

注:此方法仅作为临时 workaround,长期来看仍建议升级包。

内容的提问来源于stack exchange,提问作者AK-18

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 04:47:16