A *logical expression*, also called *a boolean expression*, is an expression that evaluates to the truth value `True`

or `False`

. They are often constructed with relational operators `==`

, `!=`

, `<`

, `>`

, `<=`

and `>=`

. Check out the various instructions and their output in the sample session below

> w <- 5 # assign a value to a variable
> is.integer(w) # w an integer object?
[1] FALSE
> is.double(w) # w a double object?
[1] TRUE
> is.numeric(w) # w a numeric object?
[1] TRUE
> w == 5 # w equal to 5?
[1] TRUE
> w == as.integer(w) # integer value of w equal to the value of w?
[1] TRUE
> w == 5.0 # w equal 5.0
[1] TRUE
> w == 5/3*3 # w exactly equal to the computed value of 5?
[1] TRUE
> w == 9/5*3*7*25/189 # w exactly equal to the computed value of 5?
[1] FALSE
> 9/5*3*7*25/189 # displayed result of a numeric calculation?
[1] 5
> w != 9/5*3*7*25/189 # w unequal to computed value close to 5?
[1] TRUE
> w == as.integer(9/5*3*7*25/189) # but equal after conversion into integer?
[1] TRUE
> w > 5 # w greater than 5?
[1] FALSE
> w <= 5 # w less than or equal to 5?
[1] TRUE
> w >= 5 # w greater than or equal
[1] TRUE

Logical expressions can be combined with logical operators `&`

, `|`

and `!`

for "and", "or", and "not", respectively. The interactive R session below illustrates this.

> ! TRUE
[1] FALSE
> ! FALSE
[1] TRUE
> for (b1 in c(TRUE,FALSE)) {
+ for (b2 in c(TRUE, FALSE)) {
+ cat(b1,"&",b2, "-->", b1 & b2, "\n")
+ cat(b1,"|",b2, "-->", b1 | b2, "\n")
+ }
+ }
TRUE & TRUE --> TRUE
TRUE | TRUE --> TRUE
TRUE & FALSE --> FALSE
TRUE | FALSE --> TRUE
FALSE & TRUE --> FALSE
FALSE | TRUE --> TRUE
FALSE & FALSE --> FALSE
FALSE | FALSE --> FALSE

In this example we use a systematic iteration of the choice of truth values from a list via a nested `for`

statement to find all cases with the `&`

and `|`

operator to walk by. The results are summarised in the table below; in this table, \(b_1\) and \(b_2\) are boolean expressions that can take values `TRUE`

and `FALSE`

and we indicate what the result would be when the logical operator `&`

, `|`

and `!`

were applied.

\[\begin{array}{c|c||c|c|c}

b_1 & b_2 & b_1\mathtt{\;\&\;}b_2 & b_1\mathtt{\;|\;}b_2 &\mathtt{!\;}b_1 \\ \hline\hline

\text{TRUE} & \text{TRUE} & \text{TRUE} & \text{TRUE} & \text{FALSE}\\ \hline

\text{TRUE} & \text{FALSE} & \text{FALSE} & \text{TRUE} & \text{FALSE}\\ \hline

\text{FALSE} & \text{TRUE} & \text{FALSE} & \text{TRUE} & \text{TRUE}\\ \hline

\text{FALSE} & \text{FALSE} & \text{FALSE} & \text{FALSE} & \text{TRUE}

\end{array}\]

It is also good to know that R stops evaluating as soon as the final result of a logical expression is known. So the code below works just fine, even though \(x\) has the value \(0\) and in principle division by zero could occur in the execution of the last instruction.

> x <- 0
> x != 0 & 1/x > 0
[1] FALSE