What is the Logical OR Operator in R

The OR in R is a built-in logical operator that “returns TRUE if one of the conditions is TRUE”. If both conditions are FALSE, they will return FALSE. This means TRUE | TRUE returns TRUE and FALSE | FALSE returns FALSE, but TRUE | FALSE and FALSE | TRUE returns TRUE.

Syntax

x | y

Return Value

It returns TRUE if x or y is TRUE.

Example 1: Simple R program to demonstrate the use of OR

Let’s define two logical vectors which will contain logical values.

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

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

The OR operator( | ) performs an element-wise operation on the vectors.

Let’s use the OR operator and see the output.

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

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

x | y

Output

[1] TRUE TRUE TRUE FALSE

Example 2: Using the OR operator in different contexts

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

k <- 19

k < 21 | k > 10

Output

[1] TRUE

Logical Operators in R

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

Operators & and | perform the element-wise operation, producing results with a more extended operand length.

But && and || examine only the first element of the operands resulting in a single logical vector.

Therefore, zero is considered FALSE, and non-zero numbers are taken as TRUE.

Related posts

Not equal in R

Not in R

Leave a Comment