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

Hans W Borchers hwborchers at googlemail.com
Mon Apr 4 05:25:10 CEST 2011


eric <ericstrom <at> aol.com> writes:

> 
> 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)
> return(d$root)
> 
> 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.
> 

Do not modify uniroot(). Use 'try' or 'tryCatch', for example

    	e <- try( d <- uniroot(k, c(.001, 250), tol=.05), silent = TRUE )
	if (class(e) == "try-error") {
		return(0.0001)
	} else {
		return(d$root)	
	}

--Hans Werner



More information about the R-help mailing list