Using logical functions

A logical vector only takes TRUE or FALSE and is mostly used to filter data. In practice, it is common to create joint conditions by multiple logical vectors where a number of logical operators and functions may involve.

Logical operators

Like many other programming languages, R enables a few operators to do basic logical calculations. The following table demonstrates what they do:

Symbol

Description

Example

Result

&

Vectorized AND

c(T, T) & c(T, F)

c(TRUE, FALSE)

|

Vectorized OR

c(T, T) | c(T, F)

c(TRUE, TRUE)

&&

Univariate AND

c(T, T) && c(F, T)

FALSE

||

Univariate OR

c(T, T) || c(F, T)

TRUE

!

Vectorized NOT

!c(T, F)

c(FALSE, TRUE)

%in%

Vectorized IN

c(1, 2) %in% c(1, 3, 4, 5)

c(TRUE, FALSE)

Get Learning R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.