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

R语言循环查找Football表起止年份行号报错及优化方案咨询

问题解决:获取足球数据中起止年份的行号

一、修复for循环代码

你的代码报错核心原因有两个:

  1. R中判断相等要用双等号==,单等号=是赋值操作,if条件里不能用赋值,这就是报错unexpected '='的直接原因。
  2. for循环的括号未闭合,for (i in 1:nrow(Football)末尾少了一个)。

修复后的完整代码:

# 先对数据按Year排序,将结果存为新对象避免修改原表
Football_sorted <- Football[order(Football$Year),]

start_year <- min(Football_sorted$Year)
end_year <- max(Football_sorted$Year)

# 提前初始化变量,避免无匹配时出现未定义错误
row_of_start <- NA
row_of_end <- NA

for (i in 1:nrow(Football_sorted)) {
  if (Football_sorted$Year[i] == start_year) {
    row_of_start <- i
  }
  if (Football_sorted$Year[i] == end_year) {
    row_of_end <- i
  }
}

# 输出结果
row_of_start
row_of_end

二、无需for循环的更简洁实现

R是向量型语言,用内置函数可以大幅简化操作:

方法1:用which()精准定位

Football_sorted <- Football[order(Football$Year),]

start_year <- min(Football_sorted$Year)
end_year <- max(Football_sorted$Year)

# 获取所有匹配起止年份的行号(支持多重复年份)
row_of_start <- which(Football_sorted$Year == start_year)
row_of_end <- which(Football_sorted$Year == end_year)

如果只需要第一个匹配的行号,用which.min()/which.max()更高效:

row_of_start <- which.min(Football_sorted$Year)
row_of_end <- which.max(Football_sorted$Year)

方法2:利用排序特性直接取首尾

因为已按Year升序排序,起始年份必然在第1行,结束年份必然在最后一行:

Football_sorted <- Football[order(Football$Year),]

row_of_start <- 1
row_of_end <- nrow(Football_sorted)

这个方法效率最高,适用于确认排序后首尾行就是目标年份的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:36:22