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
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.