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

From: eric <ericstrom_at_aol.com>
Date: Sun, 03 Apr 2011 15:12:31 -0500 (CDT)

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 = max(interval),

    f.lower = f(lower, ...), f.upper = f(upper, ...), tol = .Machine$double.eps^0.25,

    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.

R-help_at_r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Sun 03 Apr 2011 - 20:39:28 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 04 Apr 2011 - 03:40:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive