[R] Catch errors

Seth Falcon sfalcon at fhcrc.org
Tue Aug 7 00:55:46 CEST 2007


Gang Chen <gangchen at mail.nih.gov> writes:

> I wanted something like this:
>
>  >tag <- 0;
>  >tryCatch(fit.lme <- lme(Beta ~ Trust*Sex*Freq, random = ~1|Subj,  
> Model), error=function(err) tag <- 1);
>
> but it seems not working because 'tag' does not get value of 1 when  
> error occurs. How can I make it work?

You can use '<<-' to assign to the parent frame like this:

        tag <- 0
        tryCatch({
            print("inside tryCatch")
            print(paste("tag", tag))
            stop("forcing an error")
        }, error=function(e) {
            print("caught an error")
            tag <<- 1
        })

But you can also use the return value of tryCatch as a return code if
that is what "tag" is.  Like this:

        fail <- TRUE
        tag <- tryCatch({
            print("inside tryCatch")
            if (fail)
              stop("forcing an error")
            0
        }, error=function(e) {
            print("caught an error")
            1
        })
        tag

+ seth

-- 
Seth Falcon | Computational Biology | Fred Hutchinson Cancer Research Center
BioC: http://bioconductor.org/
Blog: http://userprimary.net/user/



More information about the R-help mailing list