Adrian Tompkins Adrian Tompkins - 5 months ago 45
R Question

How to tell if uniroot has failed to find roots

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

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

which for my equation usually gives me two roots:

[1] 0.1000000 0.9732628

Sometimes there are no roots, but how can I test on the next line in R that that is the outcome? The result is the following:


is.nan(All) and is.null(All) return FALSE. I tried looking at the man page
and didn't see any mention of a flag for whether roots had been found or the number of roots found. I would have expected NULL as the returned value in this case.

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