## B.3 Logical Vectors

### B.3.1 Creating Logical Vectors

In R there are 3 (!) logical values: TRUE, FALSE and, I don’t know, NA maybe?

c(TRUE, FALSE, TRUE, NA, FALSE, FALSE, TRUE)
##   TRUE FALSE  TRUE    NA FALSE FALSE  TRUE
(x <- rep(c(TRUE, FALSE, NA), 2))
##   TRUE FALSE    NA  TRUE FALSE    NA
mode(x)
##  "logical"
class(x)
##  "logical"
length(x)
##  6

By default, T is a synonym for TRUE and F for FALSE. This may be changed though so it’s better not to rely on these.

### B.3.2 Logical Operations

Logical operators such as & (and) and | (or) are performed in the same manner as arithmetic ones, i.e.:

• they are elementwise operations and
• recycling rule is applied if necessary.

For example,

TRUE & TRUE
##  TRUE
TRUE & c(TRUE, FALSE)
##   TRUE FALSE
c(FALSE, FALSE, TRUE, TRUE) | c(TRUE, FALSE, TRUE, FALSE)
##   TRUE FALSE  TRUE  TRUE

The ! operator stands for logical elementwise negation:

!c(TRUE, FALSE)
##  FALSE  TRUE

Generally, operations on NAs yield NA unless other solution makes sense.

u <- c(TRUE, FALSE, NA)
v <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, NA, NA, NA)
u & v # elementwise AND (conjunction)
##   TRUE FALSE    NA FALSE FALSE FALSE    NA FALSE    NA
u | v # elementwise OR  (disjunction)
##   TRUE  TRUE  TRUE  TRUE FALSE    NA  TRUE    NA    NA
!u    # elementwise NOT (negation)
##  FALSE  TRUE    NA

### B.3.3 Comparison Operations

We can compare the corresponding elements of two numeric vectors and get a logical vector in result. Operators such as < (less than), <= (less than or equal), == (equal), != (not equal), > (greater than) and >= (greater than or equal) are again elementwise and use the recycling rule if necessary.

3 < 1:5 # c(3, 3, 3, 3, 3) < c(1, 2, 3, 4, 5)
##  FALSE FALSE FALSE  TRUE  TRUE
1:2 == 1:4 # c(1,2,1,2) == c(1,2,3,4)
##   TRUE  TRUE FALSE FALSE
z <- c(0, 3, -1, 1, 0.5)
(z >= 0) & (z <= 1)
##   TRUE FALSE FALSE  TRUE  TRUE

### B.3.4 Aggregation Functions

Also note the following operations on logical vectors:

z <- 1:10
all(z >= 5) # are all values TRUE?
##  FALSE
any(z >= 5) # is there any value TRUE?
##  TRUE

Moreover:

sum(z >= 5) # how many TRUE values are there?
##  6
mean(z >= 5) # what is the proportion of TRUE values?
##  0.6

The behaviour of sum() and mean() is dictated by the fact that, when interpreted in numeric terms, TRUE is interpreted as numeric 1 and FALSE as 0.

as.numeric(c(FALSE, TRUE))
##  0 1

Therefore in the example above we have:

z >= 5
##   FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
as.numeric(z >= 5)
##   0 0 0 0 1 1 1 1 1 1
sum(as.numeric(z >= 5)) # the same as sum(z >= 5)
##  6

Yes, there are 6 values equal to TRUE (or 6 ones after conversion), the sum of zeros and ones gives the number of ones.