[R] how to use try()

Thomas Lumley tlumley at u.washington.edu
Mon Feb 9 23:15:32 CET 2004


On Mon, 9 Feb 2004, r.ghezzo wrote:

> Hello, I have a program with this section:
> ..
> for(i in 1:20){
>    lo <- nls(y~y0+a/(1+(x/x0)^b),start=list(y0=0.1,a=a0,x0=x00,b=-8.1))
>    beta[i] <- lo$m$getPars()[4]
> }
> ..
> If the fit works this is OK but if the fit fails, the whole program
> fails so:
> ..
> for(i in 1:20){
>    try(lo <-
> nls(y~y0+a/(1+(x/x0)^b),start=list(y0=0.1,a=a0,x0=x00,b=-8.1)))
>    beta[i] <- lo$m$getPars()[4]
> }
> ..
> but the try catches the error in nls and beta[i] gets assigned beta[i-1]
> from the previous loop. This is bad but no so bad as it can be checked,


You want either both assignments inside the try()
try({
	lo<-nls(....)
	beta[i]<-lo$m$getPars(4)
})

or both outside

lo<- try(nls(....))
if (inherits(lo,"try-error")) beta[i]<-NA else beta[i]<-lo$m$getPars()[4]


	-thomas




More information about the R-help mailing list