What I would like to do is test whether a matrix is positive definite using the command chol() in R. However, if the chol() command produces an error I would like it to output false rather than producing an error and stopping the code from running. Is there an easy way to do this? I have been messing around with the command try() but it still gives me an error.
For example, if I have the matrix:
mat=matrix(c(1,2,3,1,2,3,5,5,5),nrow=3,ncol=3,byrow=F)
try(chol(mat))
this still produces an error "Error in chol.default(mat) :
the leading minor of order 3 is not positive definite."
How can I get this to produce FALSE instead of this error?
Use tryCatch, and define a handler to use in the event of an error:
tryCatch(chol(mat), error=function(e) FALSE)
Related
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.
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.
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().
I am new to R, and learning it online by trying out some simple code
I read try() allows to ignore any error and continue. So I tried this:
When I put log() inside try(), I was still getting the same output;
I was expecting something like:
Error in log(x) : non-numeric argument to mathematical function
[1] 10
But that 10 is not appearing in the output. Why is this so?
You need source("C:/Mahesh/workspaces/r/temp.r", echo = TRUE)
I am new to programming in R, I am running a loop in R and try to output the result into a dataframe. But I encounter some error I am not able to solve it myself, it would be great if someone can have a look and give me some hints as to how to solve the problem. The process runs until it encounters a "Error" output from one of the loop.
Basically the loop stops producing output to the dataframe and it stops at the point where the loop encounters the error of:
Error in start:end : NA/NaN argument
This is my loop script:
for (i in seq(2,880)){
rscheck<-as.data.frame(cbind(as.matrix(chr1only[,i]), chr1only$SIF1))
rscheck$V2<-as.numeric(as.character(rscheck$V2))
rscheck<-na.omit(rscheck)
pvaluelevenetest2[i-1,1]<-lawstat::levene.test(rscheck$V2, rscheck$V1,correction.method="zero.correction", location="median")$p.value
}
I have the pvaluelenetest2 dataframe contains loop 1 to loop 856 result. But afterward, there is no more result. The dimension of the pvaluelenvenetest2 data is only 1 by 856 (so nothing was returned to the pvaluelentest2 dataframe after the very last non-error test).
I then test the 858th column without using loop and indeed the levene's test produces NA values and gives me this error:
Error in start:end : NA/NaN argument
So I am just wondering is there anyway the loop can continues when it encounters such an error?
thank you
So your loop is stopping because the levene function is throwing an error. You could write a tryCatch block in R to handle the error:
How to write trycatch in R
But wouldn't it be better to to find out why the function is crashing and fix the inputs, or filter out bad inputs to begin with?
For example, add code to check if rscheck$V2 or rscheck$V1 is NA before calling levene. Is it possible that rscheck$V2 contains some characters which can't be converted to numbers, causing the introduction of the NA?