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.
Logical vectors
As well as numerical vectors, R allows manipulation of logical
quantities. The elements of a logical vector can have the values
TRUE
, FALSE
, and NA
(for "not available", see
below). The first two are often abbreviated as T
and F
,
respectively. Note however that T
and F
are just
variables which are set to TRUE
and FALSE
by default, but
are not reserved words and hence can be overwritten by the user. Hence,
you should always use TRUE
and FALSE
.
Logical vectors are generated by conditions. For example
> temp <- x > 13
sets temp
as a vector of the same length as x
with values
FALSE
corresponding to elements of x
where the condition
is not met and TRUE
where it is.
The logical operators are <
, <=
, >
, >=
,
==
for exact equality and !=
for inequality.
In addition if c1
and c2
are logical expressions, then
c1 & c2
is their intersection ("and"), c1 | c2
is their union ("or"), and !c1
is the negation of
c1
.
Logical vectors may be used in ordinary arithmetic, in which case they
are coerced into numeric vectors, FALSE
becoming 0
and TRUE
becoming 1
. However there are situations where
logical vectors and their coerced numeric counterparts are not
equivalent, for example see the next subsection.