Adrian Tompkins Adrian Tompkins - 5 months ago 29
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:

[1] 0.1000000 0.9732628

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


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download