[R] priority of operators in the FOR ( ) statement

Duncan Murdoch murdoch at stats.uwo.ca
Tue Aug 23 12:44:15 CEST 2005


Ravi.Vishnu at outokumpu.com wrote:
> Dear All,
> I spent an entire evening in debugging a small, fairly simple program in R 
> - without success. It was my Guru in Bayesian Analysis, Thomas Fridtjof, 
> who was able to diagonose the problem. He said that it took a long time 
> for him also to locate the problem.
> This program illustrates in some ways the shortcomings of the error 
> messages that R responds with. 

To summarize:  you assumed that 1:nr-1 was equivalent to 1:(nr-1), 
rather than (1:nr)-1 (as documented).  This led to indexing by 0,
which (as is documented) gives a zero length vector.  R responded with 
the error message

>         missing value where TRUE/FALSE needed

when you used this in a test.  That seems like an appropriate error 
message to me.  I don't know any system that would respond better to 
user errors in operator priority:  those almost always lead to obscure 
errors, because the expression you write is often syntactically correct 
but logically wrong.

> 2. Faced with a similiar problem in the future, what is a smart way of 
> debugging in R to locate a problem. 

Use traceback() to isolate the location of the error, then debug() to 
single step through the function until you get to the error location. 
At that point, examine the values of the expressions involved in the 
calculation, and make sure they are as expected.

And in general:  if you aren't sure of the relative priority of two 
operators, use parentheses.  1:(nr-1) would work regardless of whether : 
or - had higher priority.  Or, in extreme cases, read the documentation.

Duncan Murdoch




More information about the R-help mailing list