True or false values are represented by the logical type.
It contains only two values: TRUE and FALSE.
TRUE
#> [1] TRUE
FALSE
#> [1] FALSE
typeof(TRUE)
#> [1] "logical"
There are five Boolean operators in R.
!TRUE # FALSE (not)
TRUE && FALSE # FALSE (scalar and)
TRUE || FALSE # TRUE (scalar or)
TRUE & FALSE # FALSE (vector and)
TRUE | FALSE # TRUE (vector or)
&& and & are Boolean "and".
They evaluate to TRUE if the expressions on both sides of && are TRUE.
|| and | are Boolean "or".
They evaluate to TRUE if an expression on either side of || is TRUE.
Note that there are two sets of and/or operators.
This distinction will become important, and probably clearer, in the vector-filtering concept.
Using & and | on single values works in the above example, because these are handled as length-1 vectors.
The behavior is subtly different to double-character operators, as only the latter are "short-circuiting": the value on the right is not evaluated if the left value is sufficient to determine the result.
Thus TRUE || anything is always TRUE no matter what logical expression anything represents, so the anything is ignored.
Using && or || on vectors (length 2 or more) means that only the first element is used in the comparison, yielding a single TRUE/FALSE and probably a warning message.
This is probably not what you intended.
! is Boolean "not".
It exchanges TRUE and FALSE values.
!TRUE
#> [1] FALSE
!FALSE
#> [1] TRUE
For longer and more complicated expressions, it is best to use parentheses to make your intention clear.
(TRUE || FALSE) && (FALSE && TRUE)
#> [1] FALSE
TRUE || FALSE && (FALSE && TRUE)
#> [1] TRUE
There is no infix operator for exclusive or (i.e. A OR B, but not both). The xor() function can be used in this case.
xor(TRUE, FALSE)
#> [1] TRUE
xor(TRUE, TRUE)
#> [1] FALSE