r - 如何绕过R中的for循环中的错误?

标签 r for-loop error-handling

我创建了一个for循环,将目录中的多个csv文件合并到一个表中。在某些情况下,尚未创建循环中指示的文件。当文件不存在时,循环将产生错误,并且不会合并任何文件。我正在尝试调整代码,以便循环在为文件保留的矩阵部分中插入“NULL”或“错误”。

这是原始代码:

COMP_raw <- cbind(m, matrix(-9999, ncol = length(dirnames), nrow = 169))
setwd() #actual wd is removed for posting

for(i in length(dirnames)){
  j<-dirnames[1] #Take the directory folder name
  id<-gsub("_.*$","",dirnames[1]) #Take the numeric identifier of the indicator
  fpath <- file.path(paste(j,"/",id,"_2016",".csv", sep = "")) #Merge the directory folder name and desired csv to a file path format
  data<-read.csv(fpath,header = TRUE, as.is = TRUE)
  last <- max(ncol(data))
  COMP_raw[,(1+1)] <- data[,last]
  colnames(COMP_raw)[(1+1)] <- names(data[last])
}

上面的代码适用于目录中实际存在“fpath”的每个循环。如果csv不存在,则会出现以下消息。
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file '2.1_PermitIndirectCosts/2.1_2016.csv': No such file or directory

我查看了其他一些帖子以了解如何解决该问题,并尝试了以下操作
COMP_raw <- cbind(m, matrix(-9999, ncol = length(dirnames), nrow = 169))

for(i in length(dirnames)){
  j<-dirnames[1] #Take the directory folder name
  id<-gsub("_.*$","",dirnames[1]) #Take the numeric identifier of the indicator
  fpath <- file.path(paste(j,"/",id,"_2016",".csv", sep = "")) #Merge the directory folder name and desired csv to a file path format
  possibleerror<- tryCatch(data<-read.csv(fpath,header = TRUE, as.is = TRUE),silent = TRUE),
           error=function(e) e
  )
           if(!inherits(possibleerror,"error"))
  {last <- max(ncol(data))
  COMP_raw[,(1+3)] <- data[,last]
  colnames(COMP_raw)[(1+3)] <- names(data[last])}
}

但这仍然会产生错误

最佳答案

怎样使用 file.exists() 呢?

file.exists returns a logical vector indicating whether the files named by its argument exist.


COMP_raw <- cbind(m, matrix(-9999, ncol = length(dirnames), nrow = 169))
setwd() #actual wd is removed for posting

for(i in length(dirnames)){
    j <- dirnames[1] #Take the directory folder name
    id <- gsub("_.*$","",dirnames[1]) #Take the numeric identifier of the indicator
    fpath <- file.path(paste(j,"/",id,"_2016",".csv", sep = "")) #Merge the directory folder name and desired csv to a file path format

    #Checks if file exists if not, assign NULL
    if(file.exists(fpath)){
        data <- read.csv(fpath,header = TRUE, as.is = TRUE)
        last <- max(ncol(data))
        COMP_raw[,(1+1)] <- data[,last]
        colnames(COMP_raw)[(1+1)] <- names(data[last])
    } else{
        colnames(COMP_raw)[(1+1)] <- NULL 
    } 
}

关于r - 如何绕过R中的for循环中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35487636/

相关文章:

r - 错误: 'shuffle' is not an exported object from 'namespace:merTools'

r - 为什么 ggplot 在指定其他颜色时使用默认颜色?

python - Pandas 将 nan 替换为基于另一列的第一个非 nan 值

c++ - 无法填充 C++ 数组,每个索引处只有最后一项

drupal - 注意 Drupal 中的 : unserialize() [function. 反序列化]

python - python中间件捕获错误?

sql - 在 ASP 3.0(经典)上捕获 SQL 错误并返回特定的 HttpStatus

r - 如何使用 R 以摘要格式构造数据

python - 避免 FOR 循环将多个字符串 append 到列表

r - 有什么方法可以从lme4 mer模型拟合对象生成LaTeX表?