R Language The logical class Logical operators

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

There are two sorts of logical operators: those that accept and return vectors of any length (elementwise operators: !, |, &, xor()) and those that only evaluate the first element in each argument (&&, ||). The second sort is primarily used as the cond argument to the if function.

Logical OperatorMeaningSyntax
!Not!x
&element-wise (vectorized) andx & y
&&and (single element only)x && y
|element-wise (vectorized) orx | y
||or (single element only)x || y
xorelement-wise (vectorized) exclusive ORxor(x,y)

Note that the || operator evaluates the left condition and if the left condition is TRUE the right side is never evaluated. This can save time if the first is the result of a complex operation. The && operator will likewise return FALSE without evaluation of the second argument when the first element of the first argument is FALSE.

> x <- 5
> x > 6 || stop("X is too small")
Error: X is too small
> x > 3 || stop("X is too small")
[1] TRUE

To check whether a value is a logical you can use the is.logical() function.



Got any R Language Question?