Sometimes when I am running lots of long programs I think it would be nice if there was a statement or command I could add to the bottom of a file that would tell me whether R returned any error messages (or warning messages) while running a file.
I always scroll up through all of the code to visually check for error messages or warnings and keep thinking it would be nice if R simply told me at the bottom of the code whether any error messages or warnings occurred.
Can R do that? I suppose even if R can do that I would need a while to develop trust in the command line to catch all error messages or warning messages.
With SAS I used to use the find command and search the log window for the word ‘Error’ or ‘Warning’.
Thanks for any thoughts or advice about this.
Here is a very simple example of R code that returns 3 error messages.
x <- c(1,2,3,4)
y <- c(3,4)
z <- x / y
a <- matrix(x, nrow=2, byrow=T)
b <- matrix(x, nrows=2, byrow=T)
z x a
z * a
I assume you are running from a GUI, where errors are not fatal. Here is a solution making use of options(error). The error handler is replaced by a function that increments a variable:
.error.count <- 0 old.error.fun <- getOption("error") new.error.fun <- quote(.error.count <- .error.count + 1) options(error = new.error.fun) ### your code here ### x <- c(1,2,3,4) y <- c(3,4) z <- x / y zz a <- matrix(x, nrow=2, byrow=T) b <- matrix(x, nrows=2, byrow=T) z x a z * a ###################### cat("ERROR COUNT:", .error.count, "\n") options(error = old.error.fun) rm(.error.count, old.error.fun, new.error.fun)
this is not a good example, because when i run it, it stops on the first error. however, the general question is probably better solved by the OS and the standard file descriptors. specifically, R will output its normal output to stdout, and its warnings and errors to stderr, and you can deal with those streams separately rather than seeing them together. for example, you can send stdout to a file and keep stderr in the terminal:
Rscript myfile.R 1>output.txt
I get this functionality primarily by using
source() to run code; i.e., just dump your code into a file and then run:
in R, which returns:
Error in source("yourscript.r") : yourscript.r:7:3: unexpected symbol 6: b <- matrix(x, nrows=2, byrow=T) 7: z x ^
It doesn't return all the errors in one pass - syntax errors will stop the file from executing at all, unlike checkorbored's Rscript method that runs and then gives you the first error (see
?source for more details). But it might serve your purposes.
similar to @checkorboard
what I do is put the code in a text file, say "yourscript.r" and then run:
R CMD BATCH yourscript.r &
This will automatically create a file like yourscript.rout with the output of the program and you can easily
grep to see if there was an error.