user3420448 user3420448 - 11 months ago 52
R Question

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

I am trying condition handling and recovery for the first time in R. I want to use

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
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
function properly or if there is any other way to do it. Any help is appreciated. Thanks in advance.

Answer Source

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)