[R] Catch errors
Gang Chen
gangchen at mail.nih.gov
Tue Aug 7 16:28:16 CEST 2007
Seth and Stephen,
Thanks a lot for the explanation and help! I really appreciate it.
Gang
On Aug 6, 2007, at 6:41 PM, Stephen Tucker wrote:
> That's because tag <- 1 is evaluated in a local environment (of the
> function)
> - once function(err) exits, the information is lost. Try R's <<-
> operator:
>
> tag <- 0
> tryCatch(fit.lme <- lme(Beta ~ Trust*Sex*Freq, random = ~1|Subj,
> Model), error=function(err) tag <<- 1)
On Aug 6, 2007, at 6:55 PM, Seth Falcon wrote:
> 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