Single vs Double logical operators in R

Author

Nitesh

The key difference between the single and double operators is that the single operators evaluate all elements of the vectors, while the double operators only evaluate the first element of each vector.

The double vertical bar || and the double ampersand && are known as short-circuit operators. These operators only evaluate the first element of each vector, and then immediately return a result without evaluating the remaining elements, as long as the result can be determined based on the first element.

Single operator

# OR operator (|)
x <- c(TRUE, TRUE, FALSE, FALSE)
y <- c(TRUE, FALSE, TRUE, FALSE)
# z is now c(TRUE, TRUE, TRUE, FALSE)
(z <- x | y)
[1]  TRUE  TRUE  TRUE FALSE
# AND operator (&)
x <- c(TRUE, TRUE, FALSE, FALSE)
y <- c(TRUE, FALSE, TRUE, FALSE)
# z is now c(TRUE, FALSE, FALSE, FALSE)
(z <- x & y)
[1]  TRUE FALSE FALSE FALSE

In the first example, the single OR operator | evaluates each element of the input vectors x and y and returns a logical vector z of the same length as the input vectors, where each element results from the corresponding OR operation.

In the second example, the single AND operator & also evaluates each element of the input vectors x and y and returns a logical vector z of the same length as the input vectors, where each element results from the corresponding AND operation.

Double operator

On the other hand, the double vertical bar || and the double ampersand && are known as short-circuit operators. Remember that most IF statements are short-circuited operations.

# Short-circuit OR operator (||)
x <- c(TRUE, FALSE, FALSE, FALSE)
y <- c(FALSE, TRUE, FALSE, FALSE)
# z is now TRUE because the first element of x is TRUE
(z <- x || y)
Warning in x || y: 'length(x) = 4 > 1' in coercion to 'logical(1)'
[1] TRUE
# Short-circuit AND operator (&&)
x <- c(FALSE, TRUE, TRUE, TRUE)
y <- c(TRUE, FALSE, TRUE, TRUE)
# z is now FALSE because the first element of x is FALSE
(z <- x && y)
Warning in x && y: 'length(x) = 4 > 1' in coercion to 'logical(1)'
[1] FALSE

In the first example, the short-circuit OR operator || only evaluates the first element of x and y, and returns TRUE because the first element of x is TRUE.

In the second example, the short-circuit AND operator && only evaluates the first element of x and y, and returns FALSE because the first element of x is FALSE.

Note

Warning: ‘length(x) = 4 > 1’ in coercion to ‘logical(1)’Warning: ’length(x) = 4 > 1’ in coercion to ‘logical(1)’

This is happening because we are comparing 4 logical values to 4 logical values.