The Art of R Programming

(WallPaper) #1
You may recall that it was used earlier in this chapter in a loop context,
as follows:

for (i in 1:length(x)) {

Beware of operator precedence issues.

>i<-2
> 1:i-1 # this means (1:i) - 1, not 1:(i-1)
[1]01
> 1:(i-1)
[1] 1

In the expression1:i-1, the colon operator takes precedence over the
subtraction. So, the expression1:iis evaluated first, returning 1:2. R then
subtracts 1 from that expression. That means subtracting a one-element vec-
tor from a two-element one, which is done via recycling. The one-element
vector (1) will be extended to (1,1) to be of compatible length with 1:2.
Element-wise subtraction then yields the vector (0,1).
In the expression1:(i-1), on the other hand, the parentheses have higher
precedence than the colon. Thus, 1 is subtracted fromi, resulting in 1:1, as
seen in the preceding example.

NOTE You can obtain complete details of operator precedence in R through the included help.
Just type?Syntaxat the command prompt.


2.4.4 Generating Vector Sequences with seq()..........................


A generalization of:is theseq()(orsequence) function, which generates a se-
quence in arithmetic progression. For instance, whereas 3:8 yields the vector
(3,4,5,6,7,8), with the elements spaced one unit apart (4−3=1,5−4=1,
and so on), we can make them, say, three units apart, as follows:

> seq(from=12,to=30,by=3)
[1] 12 15 18 21 24 27 30

The spacing can be a noninteger value, too, say 0.1.

> seq(from=1.1,to=2,length=10)
[1] 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0

One handy use forseq()is to deal with the empty-vector problem we
mentioned earlier in Section 2.1.2. There, we were dealing with a loop that
began with this:

for (i in 1:length(x))

Vectors 33
Free download pdf