squraishi
squraishi

Reputation: 43

How to implement tryCatch() in for loop using R

I've written R code using for() loop which reads some queries stored in R column of excel sheet, hits the server and saves the retrieved response in a text file. The code runs fine until the server responds with an error the loop execution stops. I tried implementing tryCatch() within my code but couldn't implement well.

Please help me implementing tryCatch() in my code which can save error in the different file and can continue the for() loop.

Code:

for (i in 1:R_column_len){
        R_column_data <- (file_data[[6]][i])
      a <- eval(parse(text = R_column_data))
      write.table(a,file = sprintf("C:/Results/F_Query_Prod_%s.txt", i))
    }

Upvotes: 1

Views: 167

Answers (1)

Martin Morgan
Martin Morgan

Reputation: 46866

Maybe this illustrates the general idea

library(futile.logger)

f <- function() {
    for (i in 1:10) {
        tryCatch({
            if (i %% 3 == 0)
                stop("my bad")
            ## normal behavior
            flog.info("i = %d", i)
        }, error = function(e) {
            ## error behavior
            flog.error("oops, i = %d: %s", i, conditionMessage(e))
        })
    }
}

producing output

> f()
INFO [2018-10-25 15:50:05] i = 1
INFO [2018-10-25 15:50:05] i = 2
ERROR [2018-10-25 15:50:05] oops, i = 3: my bad
INFO [2018-10-25 15:50:05] i = 4
INFO [2018-10-25 15:50:05] i = 5
ERROR [2018-10-25 15:50:05] oops, i = 6: my bad
INFO [2018-10-25 15:50:05] i = 7
INFO [2018-10-25 15:50:05] i = 8
ERROR [2018-10-25 15:50:05] oops, i = 9: my bad
INFO [2018-10-25 15:50:05] i = 10

Use features of futile.logger to append to file rather than the console, and to record only errors

fl <- tempfile()
flog.appender(appender.file(fl))
flog.threshold(ERROR)
f()

the result is

> readLines(fl)
[1] "ERROR [2018-10-26 06:28:37] oops, i = 3: my bad"
[2] "ERROR [2018-10-26 06:28:37] oops, i = 6: my bad"
[3] "ERROR [2018-10-26 06:28:37] oops, i = 9: my bad"

Upvotes: 2

Related Questions