Dealing with Logicals

As well as numeric and character vectors, R allows manipulation of logical quantities. The elements of a logical vector can have the values TRUE, FALSE, and NA (for “not available”). 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:

x <- 5

x > 13
## [1] 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
## [1] 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
## [1] TRUE

12 <= c(12, 11)
## [1]  TRUE FALSE

12 %in% c(12, 11, 8)
## [1] TRUE

x <- c(12, NA, 11, NA, 8)
is.na(x)
## [1] FALSE  TRUE FALSE  TRUE FALSE

Logical vectors may be used in ordinary arithmetic, in which case they are coerced into numeric vectors, 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)
## [1] 2