[R] How to say "if error"
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Jun 24 18:30:39 CEST 2010
On 24/06/2010 11:12 AM, Paul Chatfield wrote:
> On a similar issue, how can you detect a warning in a loop - e.g. the
> following gives a warning, so I'd like to set up code to recognise that and
> then carry on in a loop
>
> x<-rnorm(2);y<-c(1,0)
> ff<-glm(y/23~x, family=binomial)
>
> so this would be incorporated into a loop that might be
>
> x<-rnorm(10);y<-rep(c(1,0),5)
> for (i in 1:10)
> {ee<-glm(y~x, family=binomial)
> ff<-glm(y/23~x, family=binomial)}
>
> from which I would recognise the warning in ff and not those in ee, saving
> results from ee and not from ff. The last bit would be easy adding a line
> if(there_is_a_warning_message) {newvector<-NA} else {use results} but how do
> you detect the warning message?
>
> Thanks all for your feedback so far,
>
tryCatch(..., warning=function(w) NA)
will work. For example,
x <- rnorm(10)
y <- rep(c(1,0),5)
ee <- list()
ff <- list()
for (i in 1:10) {
ee[[i]] <- glm(y~x, family=binomial)
ff[[i]] <- tryCatch(glm(y/i ~ x, family=binomial),
warning=function(w) NA)
}
will give 10 fits in ee, but only one in ff (along with 9 NAs).
Duncan Murdoch
More information about the R-help
mailing list