[R] how to use try()

Spencer Graves spencer.graves at pdf.com
Tue Feb 10 18:22:31 CET 2004


      The "try" solutions suggested won't work in S-Plus.  If you want 
transportable code, the following worked for me just now in both S-Plus 
6.2 and R 1.8.1: 

error <- function()stop()

result <- try(error())
if(regexpr("error", casefold(class(result)))>0)
    "try trapped an error"

      Best Wishes,
      spencer graves

r.ghezzo wrote:

> Thanks to everybody who answered my question. Here are the suggestion 
> for completion sake of the archives.
> from John Fox @ Mcmaster.ca
> lo <-
> try(nls(y~y0+a/(1+(x/x0)^b),start=list(y0=0.1,a=a0,x0=x00,b=-8.1)))
> beta[i] <- if (class(lo) == "try-error") NA else lo$m$getPars()[4]
>
> from Peter Dalgaard @ biostat.ku.dk
> Just check the return value from try:
> beta[i] <- if(inherits(try(.....),"try-error")) NA else lo$etc...
>
> from Thomas Lumley @ u.washington.edu
> 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]
>
> from Sundar Dorai-Raj @ pdf.com
> if (inherits(lo,"try-error")) beta[i]<-NA else beta[i]<-lo$m$getPars()[4]
>
> also from Andrej Kveder @ zrc-sazu.si; Patric Burns @ pburns.seanet.com
> Hadley Wickham @ auckland.ac.nz;
>
> from Douglas Bates @ stat.wisc.edu
> Check the function nlsList in package nlme.  It does something very
> like what you want to do.
> It is not a good idea to use lo$m$getPars() directly.  It is better to
> use the generic function, which in this case is coef(), as in
> coef(lo)[4]
>
>
> On Mon, 09 Feb 2004 14:30:07 -0500
>  "r.ghezzo" <heberto.ghezzo at mcgill.ca> 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,
>>> Now in some cases the error is in i=1 and the program stops!!
>>> is there a way to set lo$m$getPars() to zero before the call?
>>> I tried to understand the use of tryCatch() but frankly it is above
>>> me. Sorry
>>> Thanks for any help
>>> Heberto Ghezzo
>>> Meakins-Christie Labs
>>>
>>>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list