The Art of R Programming

(WallPaper) #1
Ifxis empty, this loop should not have any iterations, but it actually
has two, since1:length(x)evaluates to(1,0). We could fix this by writing the
statement as follows:

for (i in seq(x))

To see why this works, let’s do a quick test ofseq():

> x <- c(5,12,13)
>x
[1] 51213
> seq(x)
[1]123
> x <- NULL
>x
NULL
> seq(x)
integer(0)

You can see thatseq(x)gives us the same result as1:length(x)ifxis not
empty, but it correctly evaluates to NULL ifxis empty, resulting in zero iter-
ations in the above loop.

2.4.5 Repeating Vector Constants with rep().............................


Therep()(orrepeat) function allows us to conveniently put the same con-
stant into long vectors. The call form isrep(x,times), which creates a vector
oftimes*length(x)elements—that is,timescopies ofx. Here is an example:

> x <- rep(8,4)
>x
[1]8888
> rep(c(5,12,13),3)
[1] 51213 51213 51213
> rep(1:3,2)
[1]123123

There is also a named argumenteach, with very different behavior, which
interleaves the copies ofx.

> rep(c(5,12,13),each=2)
[1] 5 5 12 12 13 13

34 Chapter 2

Free download pdf