[R] help on using try() to catch an error

Juliet Hannah juliet.hannah at gmail.com
Sat Feb 16 16:13:23 CET 2008


Dear R Users,

I incorporated the suggestions given to me, which solved the problem
of the program ending. However,
once an error occurs, and the value NA is assigned, the program does
not run correctly
after this point. All values assigned after this point are NA.

Here is my function.

getLRTp <- function(index)
{
   n <- as.matrix(table(myData[,index[1]],myData[,index[2]],permute.response))
   n[n[,1]==0] <- 1
   reduced_model <- try(glm.fit(X4,n,family=poisson(link="log")))
   full_model <- try(glm.fit(X5,n,family=poisson(link="log")));

   if (inherits(reduced_model,"try-error") || inherits(full_model,"try-error"))
   {
      p <- NA
   }
   else
   {
     p <- pchisq(reduced_model$deviance - full_model$deviance,
reduced_model$df.residual - full_model$df.residual, lower.tail= FALSE)
   }
}

which is called in this manner:

for (perm in 1:nperm)
{
  permute.response <- sample(response,replace=TRUE)
  pmatrix[perm,] <- apply(pairs.subset, 1, getLRTp)
}

Again, I have included only the relevant part of the code.

If the glm is succeeds, p is a p-value. On the occassion that it does
not, p is NA.

pmatrix (my result) ends up looking like:

       [,1]       [,2]       [,3]         [,4]       [,5]
[1,] 0.6291316 0.08900112 0.06693455 6.401101e-06 0.06865330
[2,] 0.6259834 0.21140489 0.06722201 6.401101e-06 0.06833421
[3,]        NA         NA         NA           NA         NA
[4,]        NA         NA         NA           NA         NA
[5,]        NA         NA         NA           NA         NA

It seems that after encountering an error and NA is assigned, it never
recovers. Is this is programming
error?

Thanks for your time,

Juliet



More information about the R-help mailing list