Using tryCatch to bypass the error messages with read.zoo in a loop

时间:2016-08-31 18:07:45

标签: r try-catch zoo

I am trying condition handling and recovery for the first time in R. I want to use read.zoo function in a loop to read a number of csv files with two different time formats, say format 1 and format 2. So obviously when I am using format1 in read.zoo to read a csv file in which times are in format 2 then it would give me an error, so I want to bypass that error message and want to try the format 2 inside read.zoo function. I am trying something like,

my.zoo <- tryCatch(expr = read.zoo(my.csv, format = format1),
                   error = read.zoo(my.csv, format = format2)

But I am always getting the error message about the time format regardless of time format. I am not sure if I am using the tryCatch function properly or if there is any other way to do it. Any help is appreciated. Thanks in advance.

1 个答案:

答案 0 :(得分:2)

The recovery has to be wrapped into the error function in order for tryCatch to operate properly, you can try something like this instead:

my.zoo = tryCatch(
             expr = read.zoo(my.csv, format = format1), 
             error = function(e) read.zoo(my.csv, format = format2)
          )