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

相同R代码在RStudio正常运行,Kaggle报错的原因排查

问题分析:本地RStudio正常运行的代码在Kaggle报错

问题重现

同样的代码在桌面版RStudio可正常输出结果,但在Kaggle运行时出现列索引错误。

运行代码

arm_ids <- armband %>% summarise()
str(arm_ids)
for(item in seq_along(as.vector(arm_ids[[1]]))){
    if((arm_ids[[1]][item] %in% arm_ids[[1]]) & (arm_ids[[1]][item] %in% all_activities[[1]]))
    {
      cat("Found item",item,"with id =",arm_ids[[1]][item],"\n",sep=" ")
      }
      else print("Not found")
    }

本地RStudio输出

tibble [12 × 1] (S3: tbl_df/tbl/data.frame)
 $ Id: num [1:12] 2.03e+09 2.35e+09 4.02e+09 4.39e+09 4.56e+09 ...
Found item 1 with id = 2026352035 
Found item 2 with id = 2347167796 
Found item 3 with id = 4020332650 
Found item 4 with id = 4388161847 
Found item 5 with id = 4558609924 
Found item 6 with id = 5553957443 
Found item 7 with id = 5577150313 
Found item 8 with id = 6117666160 
Found item 9 with id = 6775888955 
Found item 10 with id = 6962181067 
Found item 11 with id = 7007744171 
Found item 12 with id = 8792009665 

Kaggle报错信息

tibble [1 × 0] (S3: tbl_df/tbl/data.frame)
 Named list()
Error in `vec_as_location2_result()`:
! Can't subset columns past the end.
ℹ Location 1 doesn't exist.
ℹ There are only 0 columns.
Traceback:

1. as.vector(arm_ids[[1]])
2. arm_ids[[1]]
3. `[[.tbl_df`(arm_ids, 1)
4. tbl_subset2(x, j = i, j_arg = substitute(i))
5. vectbl_as_col_location2(j, length(x), j_arg = j_arg)
6. subclass_col_index_errors(vec_as_location2(j, n, names), j_arg = j_arg, 
 .     assign = assign)
7. withCallingHandlers(expr, vctrs_error_subscript = function(cnd) {... ... ... ...

问题根源

核心问题出在arm_ids <- armband %>% summarise()这行代码:

  • 本地环境中,旧版本dplyr的summarise()在未指定聚合函数时,可能默认保留了原数据的Id列;
  • Kaggle使用的是较新版本的dplyr,summarise()在无任何聚合操作时,会生成0列的空tibble,也就是报错里的tibble [1 × 0]。此时arm_ids[[1]]尝试访问不存在的第1列,直接触发索引错误。

另外代码中arm_ids[[1]][item] %in% arm_ids[[1]]属于冗余判断——元素必然属于自身所在的向量,完全可以删除该条件。

解决办法

明确指定需要提取的列或聚合逻辑,避免依赖版本差异的默认行为:

# 提取唯一Id值(根据需求选择)
arm_ids <- armband %>% distinct(Id)
# 若需保留所有Id(含重复),直接选列即可
# arm_ids <- armband %>% select(Id)

str(arm_ids)
for(item in seq_along(arm_ids$Id)){
    if(arm_ids$Id[item] %in% all_activities$Id)
    {
      cat("Found item", item, "with id =", arm_ids$Id[item], "\n", sep=" ")
    } else {
      print("Not found")
    }
}

这样无论在本地还是Kaggle环境,都能确保arm_ids包含Id列,彻底解决版本差异导致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:15:44