[R] How do I modify uniroot function to return .0001 if error ?

eric ericstrom at aol.com
Sun Apr 3 22:12:31 CEST 2011

I am calling the uniroot function from inside another function using these
lines (last two lines of the function) :

d <- uniroot(k, c(.001, 250), tol=.05)

The problem is that on occasion there's a problem with the values I'm
passing to uniroot. In those instances uniroot stops and sends a message
that it can't calculate the root because f.upper * f.lower is greater than
zero.  All I'd like to do in those cases is be able to set the return value
of my calling function "return(d$root)" to .0001. But I'm not sure how to
pull that off. I tried a few modifications to uniroot but so far no luck.

For convenience, the uniroot function is shown below:

uniroot <- function (f, interval, ..., lower = min(interval), upper =
    f.lower = f(lower, ...), f.upper = f(upper, ...), tol =
    maxiter = 1000) 
    if (!missing(interval) && length(interval) != 2L) 
        stop("'interval' must be a vector of length 2")
    if (!is.numeric(lower) || !is.numeric(upper) || lower >= 
        stop("lower < upper  is not fulfilled")
    if (is.na(f.lower)) 
        stop("f.lower = f(lower) is NA")
    if (is.na(f.upper)) 
        stop("f.upper = f(upper) is NA")
    if (f.lower * f.upper > 0)
        stop("f.up * f.down > 0")
    val <- .Internal(zeroin2(function(arg) f(arg, ...), lower, 
        upper, f.lower, f.upper, tol, as.integer(maxiter)))
    iter <- as.integer(val[2L])
    if (iter < 0) {
        warning("_NOT_ converged in ", maxiter, " iterations")
        iter <- maxiter
    list(root = val[1L], f.root = f(val[1L], ...), iter = iter, 
        estim.prec = val[3L])

View this message in context: http://r.789695.n4.nabble.com/How-do-I-modify-uniroot-function-to-return-0001-if-error-tp3424092p3424092.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list