Is it possible to not printing error messages when knitting an RMarkdown messages? [duplicate] - r

I am running a simulation study in R. Occassionally, my simulation study produces an error message. As I implemented my simulation study in a function, the simulation stops when this error message occurs. I know that it is bad practice to suppress errors, but at this moment to me there is no other option than to suppress the error and then go on with the next simulation until the total number of simulations I like to run. To do this, I have to suppress the error message R produces.
To do this, I tried different things:
library(base64)
suppressWarnings
suppressMessages
options(error = expression(NULL))
In the first two options, only warnings and message are suprressed, so that's no help. If I understand it correctly, in the last case, all error messages should be avoided. However, that does not help, the function still stops with an error message.
Has someone any idea why this does not work the way I expect it to work? I searched the internet for solutions, but could only find the above mentioned ways.
In the function I am running my simulation, a part of the code is analysed by the external program JAGS (Gibbs sampler) and the error message is produced by this analysis. Might this be where it goes wrong?
Note that I do not have to supress a certain/specific error message, as there are no other error messages produced, it is 'good enough' to have an option that supresses just all error messages.
Thanks for your time and help!

As suggested by the previous solution, you can use try or tryCatch functions, which will encapsulate the error (more info in Advanced R). However, they will not suppress the error reporting message to stderr by default.
This can be achieved by setting their parameters. For try, set silent=TRUE. For tryCatch set error=function(e){}.
Examples:
o <- try(1 + "a")
> Error in 1 + "a" : non-numeric argument to binary operator
o <- try(1 + "a", silent=TRUE) # no error printed
o <- tryCatch(1 + "a")
> Error in 1 + "a" : non-numeric argument to binary operator
o <- tryCatch(1 + "a", error=function(e){})

There is a big difference between suppressing a message and suppressing the response to an error. If a function cannot complete its task, it will of necessity return an error (although some functions have a command-line argument to take some other action in case of error). What you need, as Zoonekynd suggested, is to use try or trycatch to "encapsulate" the error so that your main program flow can continue even when the function fails.

Related

Suppressing error messages from external functions

I am using the function FixedPoint() from the package FixedPoint for some computations in R. Even if a fixed point of some function cannot be found, FixedPoint() still returns output (indicating the error) and, in addition, returns an error message. I want to suppress any such additional error messages from being printed. Neither try(), nor suppressWarnings(), nor suppressMessages() seem to work. Please find an example below that produces such an additional error message.
library(FixedPoint)
ell=0.95
delta=0.1
r=0.1
lambda=1
tH=1
tL=0.5
etaL=1
etaH=1
sys1=function(y){
A=y[1]
B=y[2]
TA=(etaM*(1-exp(-(lambda*A+lambda*(A+B)+2*delta)*tL))-2*lambda*A^2-lambda*A*B)/2/delta
TB=(etaM*exp(-(lambda*A+lambda*(A+B)+2*delta)*tL)*(1-exp(-(lambda*(A+B)+2*delta)*(tH-tL)))-lambda*B^2-lambda*A*B)/2/delta
return(c(TA,TB))
}
FixedPoint(sys1,c(1.90,0.04))
This seems to work:
cc <- capture.output(ff <- FixedPoint(sys1,c(1.90,0.04)),type="message")
where ff now holds the output you want. (Alternately, you could wrap capture.output(...) in invisible() rather than assigning its return value to a variable.)
The problem seems to be that the error message emanates from an un-silence-d try() clause within the package code.

Unexpected "=" in rstudio

In my code, I get the error message saying that there is an unexpected "=". I have tried running the line without certain "=", but that only causes other error messages, like "unused arguments". This is supposed to help, along with the rest of the code, with making a plot easier to read.
Here is the line of code:
Tricep.peaks <- data.frame (findpeaks(Tricep_falt, npeaks=8, minpeaksheight=.01, minpeaksdistance=freq=5))
Here is the error message:
Error: unexpected '=' in "Tricep.peaks <- data.frame (findpeaks(Tricep_falt, npeaks=8, minpeaksheight=.01, minpeaksdistance=freq="
Packages running are, signal, zoo, matlab, ggplot2, pracma, purrr, dplyr
As the error message shows, the error is caused by minpeaksdistance=freq=5 which looks like a typo to me.
According to https://www.rdocumentation.org/packages/pracma/versions/1.9.9/topics/findpeaks, the parameter is called minpeakdistance but not minpeaksdistance.
The OP probably meant minpeakdistance=5 or minpeakdistance=freq.

How can knitr know whether the R code evaluation has error?

The knitr would always evaluate the R code before formatting the output, so just wondering how can I know whether the R code evaluation has error. Thanks
Basically it boils down to three lines of code in the evaluate package. The key is withCallingHandlers(), which can be used to capture errors, messages, and warnings, etc. A minimal example:
withCallingHandlers(1 + 'a', error = function(e) {
cat('An error occurred! The error object is:\n')
str(e)
})
If you don't want the error to halt R, you can wrap the code in try().

R - Rstudio - make R play a sound if warning/error generated

I am running a script that loops over a list of stock pair combinations... occasionally the script stops running due to an error generated by differing data lengths between pair combo and I simply remove the mismatched stock from consideration):
Error in model.frame.default(formula = stckY ~ stckX + 0, drop.unused.levels = TRUE) :
variable lengths differ (found for 'stckX')
Is there any way I can make R / Rstudio play a sound when the error message occurs so that I can be alerted without having to keep my eyes on the screen while the script is looping along?
I can generate sounds linearly using:
beep <- function(n = 3){
for(i in seq(n)){
system("rundll32 user32.dll,MessageBeep -1")
Sys.sleep(.5)
}
}
beep()
but how can I do this conditional on an error message?
Building on #frankc answer and #hrbrmstr comment, a way to do this:
install.packages("beepr")
library(beepr)
options(error = beep)
try options(error = beep)
you would still need to define beep before you do this. Haven't verified this works but it should per ?options:
'error': either a function or an expression governing the handling
of non-catastrophic errors such as those generated by 'stop'
as well as by signals and internally detected errors. If the
option is a function, a call to that function, with no
arguments, is generated as the expression. The default value
is 'NULL': see 'stop' for the behaviour in that case. The
functions 'dump.frames' and 'recover' provide alternatives
that allow post-mortem debugging. Note that these need to
specified as e.g. 'options(error = utils::recover)' in
startup files such as '.Rprofile'.

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