3.1 Logical statements

A logical variable (or Boolean variable) is either 0 (false) or 1 (true).

The basic way to define a logical variable is by relational operators by comparing two expressions. For example, we often ask if a variable x is bigger than a certain number.

A more sophiciated way is to combine two simple logical statements using logical operators.

3.1.1 Relational Operators

It compares two numerical expressions and return a Boolean variable: either 0 (FALSE) or 1 (TRUE).

The following table shows the six commonly used relational operators

Relational operator Interpretation
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

Here are some examples:

x <- 1
y <- 2
x < y
## [1] TRUE
x > y
## [1] FALSE
x >= y
## [1] FALSE
x <= y
## [1] TRUE
x == y
## [1] FALSE
x != y
## [1] TRUE

Precedence of relational operators is lower than arithmetic operators. To avoid confusion, it is good practice to use brackets to control ordering. For example, if we write \(2 + 2 > 1 + 3\), then the software we do the arithmetic operators first. This implies we have \(4 > 4\), which implies a false statement.

3.1.2 Logical Operators

In practice, we often use two or more conditions to decide what to do. For example, scholarship is often given if the candidate has done well in both academic and extra-curricular activities.

To combine different conditions, there are three logical operators: (1) &&, (2) ||, and (3) !.

First, && is similar to AND in English, that is, A && B is true only if both A and B are true. Second,  is similar to OR in English, that is, A || B is false only if both A and B are false. Third, ! is similar to NOT in English, that is, !A is true only if A is false.

A B A && B A || B !A !B
false false false false true true
false true false true true false
true false false true false true
true true true true false false

Different relational operators, the precedence of logical operators can be high. While and and or operators are lower in precedence than relational operators, not has a very high precedence and almost always evaluated first. - Hence, it is always a good practice to use brackets to control operation ordering.

x <- 1 
y <- 2
x < y && x > y
## [1] FALSE
x >= y || x <= y
## [1] TRUE
!(x == y)
## [1] TRUE

3.1.3 Operators on vector

When we apply relational operations on vector directly, it would compare element by element.

x <- c(1,3) 
y <- c(4,2)
z <- c(2,4)
x < y 
## [1]  TRUE FALSE
x < z
## [1] TRUE TRUE

If we apply logical operators directly, we would only comparing the first element:

x <- c(1,3) 
y <- c(4,2)
z <- c(2,4)
(x < y) && (x < z)
## [1] TRUE
(x > y) || (x > z)
## [1] FALSE

To do comparison element by element. We use & instead of && for, and we use instead of .

x <- c(1,3) 
y <- c(4,2)
z <- c(2,4)
(x < y) & (x < z)
## [1]  TRUE FALSE
(x < y) | (x < z)
## [1] TRUE TRUE