Adrian Tompkins Adrian Tompkins - 1 month ago 12
R Question

How to tell if uniroot.all has failed to find roots

I am running

uniroot.all
from the package
rootSolve
in the following way:

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


which for my equation usually gives me two roots:

All
[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:

numeric(0)


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.all finds no roots
}