Adrian Tompkins Adrian Tompkins - 29 days ago 9
R Question

How to tell if uniroot has failed

I am running uniroot from the package rootSolve in the following way:

All <- uniroot.all(fun, c(0, 1))


which gives me usually two roots:

All
[1] 0.1000000 0.9732628


But for some parameter settings there are no roots, which is fine, but how to test for that?

All
numeric(0)


is.nan and is.null return false. I tried looking at the man page
and didn't see any mention of a flag for finding a solution.

EDIT: apologies for my confusion, I didn't realise there was a uniroot in stats too.

Answer Source

The standard approach is to check whether the vector of roots returned has zero length as suggested by @zx8754. Note that it is fastest to coerce length(All) to a logical rather than explicitly computing the comparison to 0.

if(!length(All)) {
  #handle case when uniroot finds no roots
}