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?

## [1]  TRUE FALSE  TRUE    NA FALSE FALSE  TRUE
## [1]  TRUE FALSE    NA  TRUE FALSE    NA
## [1] "logical"
## [1] "logical"
## [1] 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,

## [1] TRUE
## [1]  TRUE FALSE
## [1]  TRUE FALSE  TRUE  TRUE

The ! operator stands for logical elementwise negation:

## [1] FALSE  TRUE

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

## [1]  TRUE FALSE    NA FALSE FALSE FALSE    NA FALSE    NA
## [1]  TRUE  TRUE  TRUE  TRUE FALSE    NA  TRUE    NA    NA
## [1] 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.

## [1] FALSE FALSE FALSE  TRUE  TRUE
## [1]  TRUE  TRUE FALSE FALSE
## [1]  TRUE FALSE FALSE  TRUE  TRUE

B.3.4 Aggregation Functions

Also note the following operations on logical vectors:

## [1] FALSE
## [1] TRUE

Moreover:

## [1] 6
## [1] 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.

## [1] 0 1

Therefore in the example above we have:

##  [1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
##  [1] 0 0 0 0 1 1 1 1 1 1
## [1] 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.