Logical OR ( | ) Operator in R

You can represent the OR operator in R as “|” for element-wise comparison and “||” for a single comparison between two elements. It returns TRUE if one of the conditions is TRUE. If both conditions are FALSE, it will return FALSE.

The OR operator is similar to the AND operator, with one difference: Only one of the logical values needs to be equal to TRUE for the entire OR operation to evaluate TRUE.

In summary, TRUE | TRUE returns TRUE and FALSE | FALSE returns FALSE, but TRUE | FALSE and FALSE | TRUE returns TRUE.

Syntax

x | y

Return Value

The OR operator returns TRUE if x or y is TRUE.

Visual Representation

Visual representation of logical OR Operator in R

In the above figure, we compare two vectors, and each value is compared to the other vector’s value respectively. Only the last value of the vector has FALSE | 0, which results in FALSE because both are FALSE.

Example 1: Basic usage of OR

x <- c(TRUE, FALSE, 0, FALSE)

y <- c(FALSE, TRUE, 1, 0)

x | y

Output

[1] TRUE TRUE TRUE FALSE

Example 2: Usage with different contexts

Using the OR operator in different contexts Visually

In the above figure, we compare k’s value 19, which is < 21 or > 10.

Actually, both conditions hold TRUE; that’s why it returns TRUE.

Let’s define a variable k, assign the value 19, and then check the value.

k <- 19

k < 21 | k > 10

Output

[1] TRUE

Differences Between | and ||

The | performs element-wise comparison and is suitable for operations on vectors.

The || compares only the first elements of vectors and is primarily used in conditions where a single TRUE/FALSE result is sufficient.

Logical Operators

Operator Description
!x Not x
x | y element-wise OR
x | | y Logical OR
x & y element-wise AND
x && y Logical AND
isTRUE(x) It tests if X is TRUE

That’s all!

Leave a Comment