简体   繁体   中英

Error in tryCatch

I have a code in which with a for loop a list of files are read and analyzed . As I have to analyze several files, I want to use tryCatch for printing the name of the file that raised a problem. A common problem that my files have is that a column name is misssing, I mean, it would be in the file:

ID; close; description
1;20-12-2017;0.5;"description1"

instead of

ID; date; close; description
1;20-12-2017;0.5;"description1"

This will obviously rise an error because the number of column names doesn't match with the number of columns.

For detecting this errors I'm doing the below code:

  for (i in 1:length(files)){
    tryCatch({
    name<-as.character(files[i])
    dat<-read.table(name,header = T,sep="@",dec=",",comment.char = "")
    },
    error<-function(e){
    print("error in file",files[i])
    })

where files is a list of the names of the files analyzed.

So, I'm trying to print the file name that is causing troubles.

The traceback obtained by my code is:

3.stop("bad handler specification") 
2.tryCatch({
    name <- as.character(files[i])
    dat <- read.table(name, header = T, sep = "@", dec = ",", 
        comment.char = "") ... 
1.data_function(files) 

I've never used before tryCatch, so probably is a condition problem, but I'm not sure.

Thanks!

Update

I have a new code which is:

  for (j in 1:length(files)){

    name<-as.character(files[j])

    possibleError<-tryCatch({
        dat<-read.table(name,header = T,sep="@",dec=",",comment.char = "")
    },
    warning = function(w) {
        print(paste("Warning:", w, "in file:", name))
    },
    error<-function(e){
        print(paste("Error:", e, "in file:",name))
    },
    finally = {
        print(paste("End proc. :", name))
    }
    )


    if(!inherits(possibleError, "error")) {

        # do things
    }
    else{next}
}

Because I want to detect the files with errors, but also to continue the loop.

The problem is that it doesn't continue the loop, because there is an error in one of the files, and the error print doesn't work as well, as you can see:

[1] "End proc. : C:\\TimeSeries_RiskFactors\\20171119\\C0.GBMRISK.1100000156062.txt"
[1] "End proc. : C:\\TimeSeries_RiskFactors\\20171119\\C0.GBMRISK.1100000156063.txt"
[1] "End proc. : C:\\TimeSeries_RiskFactors\\20171220\\C0.GBMRISK.1100000156064.txt"
 Show Traceback

 Rerun with Debug
 Error in read.table(name, header = T, sep = "@", dec = ",", comment.char = "") : 
  duplicate 'row.names' are not allowed  

[1]"End proc. : C:\\TimeSeries_RiskFactors\\20171220\\C0.GBMRISK.1100000156065.txt"

Your are getting the "bad handler specification" error because of misspelled error argument to tryCatch . Only = can be used for specifying argument names, eg

tryCatch(stop("no"), error = function(e) cat("Error: ",e$message, "\\n"))

This is also why errors are not being caught. Note that specifying an argument by name is not the same as an assignment (creating a binding). In the latter, you can use <- (and it is sometimes preferred as it makes it clear it is an assignment) as well as = . In the former, you can only use = .

Not a tryCatch solution. Loop through filenames, check if it exists, then check if dataframe has the right names. Something like this (not tested):

myList <- lapply(myFiles, function(i){
  if(file.exists(i)){
    res <- paste(i, "File doesn't exist.")
  } else {
    res <- read.table(i)
    if(!identical(colnames(res), c("ID", "date", "close", "description")){
      res <- paste(i, "File wrong columns")
    }
  }
  #return
  res
}))

Then we can separate our dataframes and error messages to different lists:

# my dataframes with correct column names
myListDF <- myList[ sapply(myList, is.data.frame) ]

# failed files
myListErrors <- myList[ !sapply(myList, is.data.frame) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM