Vectors and Simple Manipulations
This section introduces the basic operations on vectors, most of which are done element-wise. Please pay attention to the recycling of vectors (usually, recycling doesn't generate an error or a warning, so it is easy to miss if it was unintended), missing values (NA), and logical vectors often used for data subsetting.
Generating regular sequences
R has a number of facilities for generating commonly used sequences
of numbers. For example 1:30
is the vector c(1, 2,
…, 29, 30)
.
The colon operator has high priority within an expression, so, for
example 2*1:15
is the vector c(2, 4, …, 28, 30)
.
Put n <- 10
and compare the sequences 1:n-1
and
1:(n-1)
.
The construction 30:1
may be used to generate a sequence
backwards.
The function seq()
is a more general facility for generating
sequences. It has five arguments, only some of which may be specified
in any one call. The first two arguments, if given, specify the
beginning and end of the sequence, and if these are the only two
arguments given the result is the same as the colon operator. That is
seq(2,10)
is the same vector as 2:10
.
Arguments to seq()
, and to many other R functions, can also
be given in named form, in which case the order in which they appear is
irrelevant. The first two arguments may be named
from=value
and to=value
; thus
seq(1,30)
, seq(from=1, to=30)
and seq(to=30,
from=1)
are all the same as 1:30
. The next two arguments to
seq()
may be named by=value
and
length=value
, which specify a step size and a length for
the sequence respectively. If neither of these is given, the default
by=1
is assumed.
For example
> seq(-5, 5, by=.2) -> s3
generates in s3
the vector c(-5.0, -4.8, -4.6, …,
4.6, 4.8, 5.0)
. Similarly
> s4 <- seq(length=51, from=-5, by=.2)
generates the same vector in s4
.
The fifth argument may be named along=vector
, which is
normally used as the only argument to create the sequence 1, 2,
…, length(vector)
, or the empty sequence if the vector is
empty (as it can be).
A related function is rep()
which can be used for replicating an object in various complicated ways.
The simplest form is
> s5 <- rep(x, times=5)
which will put five copies of x
end-to-end in s5
. Another
useful version is
> s6 <- rep(x, each=5)
which repeats each element of x
five times before moving on to
the next.