As well as numeric and character vectors, R allows manipulation of logical quantities. The elements of a logical vector can have the values
NA (for “not available”). The first two are often abbreviated as
F, respectively. Note however that
F are just variables which are set to
FALSE by default, but are not reserved words and hence can be overwritten by the user. Hence, you should always use
Logical vectors are generated by conditions. For example:
x <- 5 x > 13 ##  FALSE
The result is a logical output the same length as
x with values
FALSE corresponding to elements of
x where the condition is not met and
TRUE where it is. Thus, a vector of several elements being compared to a value will result in a logical vector with length equal to x.
x <- c(5, 14, 10, 22) x > 13 ##  FALSE TRUE FALSE TRUE
The logical operators are
== for exact equality and
!= for inequality. We can also use
%in% for group membership and
is.na for missing values.
12 == 12 ##  TRUE 12 <= c(12, 11) ##  TRUE FALSE 12 %in% c(12, 11, 8) ##  TRUE x <- c(12, NA, 11, NA, 8) is.na(x) ##  FALSE TRUE FALSE TRUE FALSE
Logical vectors may be used in ordinary arithmetic, in which case they are coerced into
FALSE becoming 0 and
TRUE becoming 1.
x <- c(5, 14, 10, 22) # how many elements in x are greater than 13? sum(x > 13) ##  2