Skip to content
Back to formatted view

Raw Message

Message-ID: <loom.20110404T050559-286@post.gmane.org>
Date: 2011-04-04T03:25:10Z
From: Hans W Borchers
Subject: How do I modify uniroot function to return .0001 if error ?

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