Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tryCatch in R not working properly

Tags:

r

try-catch

I have the following R code:

tryCatch( {pre_symbol=read.table(file=filePre,header=FALSE,sep=",")}
         , error = function(e) {loadError = TRUE} )

When the input file (filePre) is empty, the tryCatch does NOT set the global variable loadError to TRUE. This creates problems in my code (when code that executes when loadError==false assumes filePre is not empty) that the tryCatch was supposed to prevent. However, when I remove the tryCatch statement and try to load via read.Table, I get the error

Error in read.table(file = filePre, header = FALSE, sep = ",") : no lines available in input

which is expected in this case. I have no idea why this isn't working. It works for most of the other files in my set.

like image 657
Erroldactyl Avatar asked Dec 01 '22 20:12

Erroldactyl


1 Answers

You should use global assignment operator <<- here , for example:

loadError = FALSE
toto <- function(){

  tryCatch(stop("dummy error"),error=function(e)loadError <<- TRUE)
}

> toto()
> loadError
[1] TRUE
like image 147
agstudy Avatar answered Dec 03 '22 23:12

agstudy