[R] numeric(0)

(Ted Harding) Ted.Harding at nessie.mcc.ac.uk
Wed Dec 29 17:34:56 CET 2004


On 29-Dec-04 Ted Harding wrote:
> You've fallen into a classic trap: 1:length(sequence)-1 does not
> mean what one might naturally expect.
> 
>> sequence<-(1:10)
>> length(sequence)
> [1] 10
>> 1:length(sequence)-1
>  [1] 0 1 2 3 4 5 6 7 8 9
>> 1:(length(sequence)-1)
> [1] 1 2 3 4 5 6 7 8 9
> 
> In other words, "1:length(sequence)" is constructed first, then
> 1 is subtracted from every element. As a result, you tried to
> read from sequence[0], which isn't there.
> 
> However, you can make it evaluate "length(sequence)-1" before
> constructing 1:(length(sequence)-1), by using the parantheses
> to force precedence.

This got me wondering. Hence:

  > 1:2-4
  [1] -3 -2

as above. Similarly of course 1:2+4.

Likewise

  > 1:2*4
  [1] 4 8

and similarly of course

  > 1:2/4
  [1] 0.25 0.50

However:

  > 1:2^4
  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16

and not

  [1]  1 16

which has to be forced by "(1:2)^4".

So the precedence rules seem to be:

A:  Unary -
B:  ^
C:  :
D:  * /
E:  + -

The position of ":" in this surprises me, intuitively.
I can see reasons why it would be natural for ":" to come
below "Unary -" -- this makes sense of the natural "-2:2",
for instance, so that this gives "-2 -1 0 1 2" and not "-2".

However, I don't see why it was chosen to make "1:2^4" mean
"1:(2^4)" and not "(1:2)^4". My intuitive expectation is that
this should follow the pattern of 1:2*4 or 1:2+4. All three
are, after all, simply binary arithmetic operators. So I'd
have expected to find ":" at position "B", above "^" at "C",
and not between "^" and "*".

What's the best place to look for the details on operator
precedence and the like in R?

[And, just to pre-empt the suggestion: I'm very much in the
 habit of using parentheses to force precedence in all cases
 where I'm not absolutely sure of the outcome ... ]

Thanks, and best wishes to all,
Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861  [NB: New number!]
Date: 29-Dec-04                                       Time: 16:34:56
------------------------------ XFMail ------------------------------




More information about the R-help mailing list