problems with tryCatch

2

Good, I have a code in which by means of a loop they are opened and analyzed files that appear in a list. As I am going to have to analyze several files I want to print the name of the file that has problems to open. A problem that is common for files is missing a column name, for example instead of having:

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

has

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

This evidently raises an error since when reading the file it is seen that the number of column names does not correspond to the number of columns.

To detect these errors I am following the following 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 files.

So what I'm trying to do is print the name of the file on the screen.

The error that jumps me 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) 

Thank you!

    
asked by Ahinoa 12.12.2017 в 11:12
source

1 answer

1

Ahinoa, if the tryCatch() is not capturing the error, most likely it is a warning , also add a handle for these:

files = c("archivo.txt", "archivo2.txt")
for (i in 1:length(files)){
    tryCatch({
        dat<-read.table(files[i], header = T,sep=";",dec=".")
    },
    warning = function(w) {
        print(paste("Warning:", w, "in file:", files[i]))
    },
    error<-function(e){
        print(paste("Error:", e, "in file:",files[i]))
    },
    finally = {
        print(paste("Fin del proceso de :", files[i]))
    }
    )
}

The vector files corresponds to two files created according to your two examples, the archivo2.txt intentionally missing a line ending to the last record. Check the parameters of read.table because it does not correspond to the files, the separator is ; and the decimals are separated with . . On the other hand I commented that the print are poorly constructed, this: print("error in file",files[i]) does not work or you do print(c("error in file",files[i])) or much better print(paste("error in file",files[i])) .

The execution throws the following output:

[1] "Fin del proceso de : archivo.txt"
[1] "Warning: simpleWarning in read.table(files[i], header = T, sep = \";\", dec = \".\"): incomplete final line found by readTableHeader on 'archivo2.txt'\n in file: archivo2.txt"
[1] "Fin del proceso de : archivo2.txt"

We see that the second file generates a warning that is captured by tryCatch()

    
answered by 12.12.2017 / 13:49
source