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

如何修复R语言中‘recursive gc invocation’报错问题

解决write_excel_csv保存数据框列表时的recursive gc invocation报错

报错信息

wrote 7.16kB in  0s, 106.80MB/s *** recursive gc invocation
*** recursive gc invocation
*** recursive gc invocation
*** recursive gc invocation
*** recursive gc invocation

我的代码

myfiles_full_names= list.files(path="/mypath", pattern="*.csv", full.names=TRUE)

myfiles_trend_name <- list.files(path="/mypath", pattern = "*.csv") |> stringr::str_remove(".csv")

df_list_2<-lapply(myfiles_full_names , function(x) read.csv(x, sep=","))

for (i in seq_along(df_list_2)) {
  readr::write_excel_csv(df_list_2[[i]], 
                         paste0("where I want to put the csv files/",names(df_list_2)[i] ,".csv"))
}

每个数据框包含三列:Date(POSIXct类型)、id(numeric类型)、Text(character类型)。


问题原因与解决方法

问题根源

df_list_2没有设置列表元素名称,导致names(df_list_2)[i]返回NULL,生成的文件名无效,触发了write_excel_csv的垃圾回收递归调用错误。

修复方案1:给列表元素命名

  1. 为df_list_2赋予正确的名称:
    names(df_list_2) <- myfiles_trend_name
    
  2. 确保输出路径存在(避免路径不存在的额外错误):
    output_dir <- "where I want to put the csv files/"
    if (!dir.exists(output_dir)) dir.create(output_dir, recursive = TRUE)
    
  3. 修改循环代码:
    for (i in seq_along(df_list_2)) {
      readr::write_excel_csv(df_list_2[[i]], 
                             paste0(output_dir, names(df_list_2)[i], ".csv"))
    }
    

修复方案2:直接使用已有的文件名列表

跳过列表命名步骤,直接用myfiles_trend_name指定文件名:

output_dir <- "where I want to put the csv files/"
if (!dir.exists(output_dir)) dir.create(output_dir, recursive = TRUE)

for (i in seq_along(df_list_2)) {
  readr::write_excel_csv(df_list_2[[i]], 
                         paste0(output_dir, myfiles_trend_name[i], ".csv"))
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:00:06