Doing mathematics with R: Control structures
Logical expressions
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
Unlock full access