Re: [R] debugging a try() statement

From: Berwin A Turlach <>
Date: Wed, 20 Feb 2008 12:20:31 +0800

G'day Juliet,

On Tue, 19 Feb 2008 21:35:11 -0500
"Juliet Hannah" <> wrote:

> I implemented a try() statement that looks like:
> <- function(index)
> {
> reduced_model <- try(,n,family=poisson(link="log")))
> full_model <- try(,n,family=poisson(link="log")))
> if (inherits(reduced_model,"try-error") ||
> inherits(full_model,"try-error")) return(NA)
> else
> {
> p <- pchisq(reduced_model$deviance - full_model$deviance,
> reduced_model$df.residual - full_model$df.residual, lower.tail= FALSE)
> return (p)
> }
> }
> After an error occurs NA is returned. But after this occurs, all
> values returned after this remain as an NA even though this error
> should occur only 1/500 to 1/1000 times.


> Is there anything obviously incorrect with my function above.

Yes, namely:

  1. you do not assign it to any object, so how do you call it?
  2. it has a formal argument which is not used anywhere. I guess that would be considered bad programming style in any programming language.
  3. The way your code is formatted, the "return(NA)" is on the same line has the if-clause. Hence, at the end of that statement R's parser has read a complete statement which is then executed. Whence, when the parser comes across the "else", a syntax error should be produced.

Non of these would explain the problem that you mention, but point 3) raises the question why this code actually works. From what is shown, there is (at least to me) no obvious explanation for the behaviour that you see.

> If not, I will post a full example to illustrate my question.

Well, please not. :) It is pretty obvious, that the code above is derived by cut & paste from a larger body of code and does not run on its own. So there is no guarantee that this piece of the code is the one where the problem lies and you cannot seriously expect people to debug such code for you (and for that reason your previous posting probably did not get an answer).

Likewise, you should not expect people to reverse-engineer and debug a large body of code for you. You should do what the footer of e-mails to r-help requests, namely:

> PLEASE do read the posting guide
> and provide commented,
> minimal, self-contained, reproducible code.

Typically, while trying to produce such a commented, minimal, self-contained, reproducible example of the problematic code one finds the bug.


        Berwin mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Wed 20 Feb 2008 - 04:23:55 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 20 Feb 2008 - 05:30:15 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive