How to ignore error while running r script - r

I have a R script where some of scripts not run sometimes because of data unavailability. I want to ignore this error so that my script can run on cron schedule.
Script:
data1 = data1 %>% mutate(`04_Days`=paste(round(ifelse(`04 Days` %in% c(NA,"NA"),0,`04 Days`)/`Till date attempted1`*100,0)," %"))
where sometimes the variable 04_Daysis not available and I want to ignore this error while running this line.

You can use tryCatch as explained here.
If the code inside tryCatch throws an error, the error function is called. If you want to ignore the error, just leave that function empty.

Related

How to stop R from stopping execution on error?

I'm having an issue where if I execute several lines of code at once and one of them has an error, the lines below don't get executed.
For example if I have:
table(data$AGE)
table(dataREGION)
table(date$SEXE)
I get the table for the first line, and then
Error in table(dataREGION) : object 'dataREGION' not found
>
And the last line does not execute.
Does anyone know why it does that and how to fix it?
(I work with R 4.2.2 and RStudio 2022.12.0+353 "Elsbeth Geranium" Release)
Thanks!
Have a nice day,
Cassandra
Fixed: In Global Options > Console, under "Execution" uncheck the "Discard pending console input on error"
It seems like you want to use try().
try(table(data$AGE), silent = F, outFile = T)
try(table(dataREGION)) # also works without any params
try(table(date$SEXE))
You can also use tryCatch() if you want more control but it doesn't seem necessary for your purpose.
__
As for why your dataREGION doesn't exectue:
Hazarding a guess it might be because you forgot the $ between data and REGION

Is there a function in R to check if there is an error in r script or in a log?

I'm trying to create an if statement to check whether there is any errors in my R script (or error displayed on the console) and also log files if there are to have "error" in a variable and if there isn't to have "no error" in the same variable.
I looked at is.error() however I want to check if an error is shown on the console or log file.
There is no single-stop solution to the best of my knowledge. There are several things you can try:
1) Incorporate your script into your code and use tryCatch or try to catch any errors. More information on error catching and debugging in R can be found here.
2) Execute your script in the system shell via the system command and inspect output caught by setting intern=TRUE.
You can source the script in a new environment :
testscript <- function(scriptpath) {
tryCatch({
# Tests is the script runs without error
source(scriptpath, local = new.env())
message("Script OK")
},
error = function(cond){
message('Script not OK')
message(cond)
})}
for example, content of script.R :
x <- 1
y <- 2
x + z
testscript('script.R')
Script not OK
object 'z' not found

Run Multiple Scripts with Error Handling in R

I need to run two R scripts in sequence. I am not asking about running scripts in parallel.
Each script has a stop-if-error logic inside. So if I run either of them separately, the execution will halt when an error occurs. The problem is, when I put them in a wrapper code like this:
source('script1.r', echo=T)
source('script2.r', echo=T)
and when an error occurs in script1.r, R will move on to execute script2.r.
How do I tell R to stop completely and not to move on in such a scenario?
I would wrap the code in the two scripts in functions, source the scripts and then call the functions in the main file. If one function fails the script should stop.
(This may depend on how you execute the script, for example if you select code in Rstudio and run by CMD+Enter it will continue after errors.)
You could do something with try(). I put the following in script1.R:
stop("Stop")
In script2.R I have
print("A")
Then from a "master script", I call
x <- try(source("script1.R", echo = TRUE))
#>
#> > stop("Stop")
if ( !inherits(x, "try-error") ) {
source("script2.R", echo = TRUE)
}
Created on 2019-01-31 by the reprex package (v0.2.1)
If the stop() portion is called (or any error occurs), x will be of class try-error, and the second source() call will not be executed.

exit on error from noninteractive R scripts

I have a script that I run from the commandline, like
Rscript example.R
and I'd like to have it tell me some debugging information when it exits. If I don't do anything special, if it hits an error, it exits, right there, and I see the error message. So, I added
options(error=traceback)
and then it gave me not only the error message but the stack at the time of the error, very useful. Great.
But now the script continues on through to the end, tossing up a lot more errors. Why does setting the error change Rscript's behaviour on encountering an error? How do I get it to just exit after the first error, as before?
Ah-ha. The trick is to call q(). In the help for dump.frames:
options(error = quote({dump.frames(to.file = TRUE); q()}))
and to use traceback (and function instead of quote),
options(error = function(){ traceback(); q()} )
would do it.

tryCatch does not catch an error if called though RScript

I'm facing a strange issue in R.
Consider the following code (a really simplified version of the real code but still having the problem) :
library(timeSeries)
tryCatch(
{
specificWeekDay <- 2
currTs <- timeSeries(c(1,2),c('2012-01-01','2012-01-02'),
format='%Y-%m-%d',units='A')
# just 2 dates out of range
start <- time(currTs)[2]+100*24*3600
end <- time(currTs)[2]+110*24*3600
# this line returns an empty timeSeries
currTs <- window(currTs,start=start,end=end)
message("Up to now, everything is OK")
# this is the line with the uncatchable error
currTs[!(as.POSIXlt(time(currTs))$wday %in% specificWeekDay),] <- NA
message("I'm after the bugged line !")
},error=function(e){message(e)})
message("End")
When I run that code in RGui, I correctly get the following output:
Up to now, everything is OK
error in evaluating the argument 'i' in
selecting a method for function '[<-': Error in
as.POSIXlt.numeric(time(currTs)) : 'origin' must be supplied
End
Instead, when I run it through RScript (in windows) using the following line:
RScript.exe --vanilla "myscript.R"
I get this output:
Up to now, everything is OK
Execution interrupted
It seems like RScript crashes...
Any idea about the reason?
Is this a timeSeries package bug, or I'm doing something wrong ?
If the latter, what's the right way to be sure to catch all the errors ?
Thanks in advance.
EDIT :
Here's a smaller example reproducing the issue that doesn't use timeSeries package. To test it, just run it as described above:
library(methods)
# define a generic function
setGeneric("foo",
function(x, ...){standardGeneric("foo")})
# set a method for the generic function
setMethod("foo", signature("character"),
function(x) {x})
tryCatch(
{
foo("abc")
foo(notExisting)
},error=function(e)print(e))
It seems something related to generic method dispatching; when an argument of a method causes an error, the dispatcher cannot find the signature of the method and conseguently raises an exception that tryCatch function seems unable to handle when run through RScript.
Strangely, it doesn't happen for example with print(notExisting); in that case the exception is correctly handled.
Any idea about the reason and how to catch this kind of errors ?
Note:
I'm using R-2.14.2 on Windows 7
The issue is in the way the internal C code implementing S4 method dispatch tries to catch and handle some errors and how the non-interactive case is treated in this approach. A work-around should be in place in R-devel and R-patched soon.
Work-around now committed to R-devel and R-patched.
Information about tryCatch() [that the OP already knew and used but I didn't notice]
I think you are missing that your tryCatch() is not doing anything special with the error, hence you are raising an error in the normal fashion. In interactive use the error is thrown and handled in the usual fashion, but an error inside a script run in a non-interactive session (a la Rscript) will abort the running script.
tryCatch() is a complex function that allows the potential to trap and handle all sorts of events in R, not just errors. However by default it is set up to mimic the standard R error handling procedure; basically allow the error to be thrown and reported by R. If you want R to do anything other than the basic behaviour then you need to add a specific handler for the error:
> e <- simpleError("test error")
> tryCatch(foo, error = function(e) e,
+ finally = writeLines("There was a problem!"))
There was a problem!
<simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'foo'
not found>
I suggest you read ?tryCatch in more detail to understand better what it does.
An alternative is to use try(). To modify your script I would just do:
# this is the line with the uncatchable error
tried <- try(currTs[!(as.POSIXlt(time(currTs))$wday %in% specificWeekDay),] <- NA,
silent = TRUE)
if(inherits(tried, "try-error")) {
writeLines("There was an error!")
} else {
writeLines("Everything worked fine!")
}
The key bit is to save the object returned from try() so you can test the class, and to have try() operate silently. Consider the difference:
> bar <- try(foo)
Error in try(foo) : object 'foo' not found
> bar <- try(foo, silent = TRUE)
> class(bar)
[1] "try-error"
Note that in the first call above, the error is caught and reported as a message. In the second, it is not reported. In both cases an object of class "try-error" is returned.
Internally, try() is written as a single call to tryCatch() which sets up a custom function for the error handler which reports the error as a message and sets up the returned object. You might wish to study the R code for try() as another example of using tryCatch().

Resources