【问题标题】:Continue with Loop even if Excel not have tab即使 Excel 没有选项卡,也继续循环
【发布时间】:2019-08-29 16:42:54
【问题描述】:

我是 R 新手,正在尝试编写一些代码来遍历我的文件夹中的所有文件,然后提取与某个选项卡关联的所有数据。但是,此选项卡可能不会出现在我存储在此文件夹中的所有文件中。为了解决这个问题,我使用了 Try-Catch 功能,但仍然遇到问题。

如果选项卡不存在,我还需要做什么才能循环遍历数据,而不是加载它?

这是我尝试过的:

for (i in 1:nrow(filesinfolderfull_list)){
  print(filesinfolder_list[i])
  i_ddolv_temp <- tryCatch (
    { read_excel(filesinfolderfull_list$datafiles[i], sheet="Display-OLV Reporting",col_names=TRUE,skip=4)},
error = function(e){print("skip")}
  )
  templateDDOLV_df<- bind_rows(templateDDOLV_df,i_ddolv_temp)  
}

【问题讨论】:

    标签: r for-loop import error-handling


    【解决方案1】:

    我从您的解释中得知,有些 Excel 没有"Display-OLV Reporting" 表。为什么不先用excel_sheets 查找,然后提取TRUE。类似的东西:

    for (i in 1:nrow(filesinfolderfull_list)){
      print(filesinfolder_list[i])
      if ("Display-OLV Reporting"%in%excel_sheets(read_excel(filesinfolderfull_list$datafiles[i]){
          i_ddolv_temp <- read_excel(filesinfolderfull_list$datafiles[i], sheet="Display-OLV Reporting",col_names=TRUE,skip=4)
          templateDDOLV_df<- bind_rows(templateDDOLV_df,i_ddolv_temp) 
       } 
    }
    

    您可以使用一个变量来不读取每个 excel 两次

    【讨论】:

    • 啊哈!谢谢!这解决了我的问题。
    • 没问题,如果这解决了您的问号,则将其标记为已接受的答案以关闭问题。
    猜你喜欢
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2017-04-10
    • 2019-08-09
    • 2016-09-10
    相关资源
    最近更新 更多