Chapter 2 Logical Expressions and If-Else Statements in R
2.1 Logical Expression in R
A Logical expression is an expression that evaluates to either TRUE or FALSE.
The following are examples of logical expressions in R:
4 > 2
3 <= 5
15.0 + 1.3*1.3 > 17.0
"cat" == "dog"
Each of the above expressions will evaluate to either TRUE or FALSE if you run them in R.
## [1] TRUE
## [1] TRUE
## [1] FALSE
## [1] FALSE
- Most logical expressions are constructed by using some combination of:
- Comparison operators (<, <=, ==, !=)
- Logical operators (and, or, not) (in R: &&, ||, !)
2.1.1 Comparison Operators
Operator | Meaning | Example | Result |
---|---|---|---|
< | Less than | 5 < 3 | FALSE |
> | Greater than | 5 > 3 | TRUE |
<= | Less than or equal to | 3 <= 6 | TRUE |
>= | Greater than or equal to | 4 >= 3 | TRUE |
== | Equal to | 2 == 2 | TRUE |
!= | Not equal to | ‘str’ != ‘stR’ | TRUE |
2.1.2 Logical Operators
The first main logical operator we will discuss is the logical AND
In R, the logical operator
&
is used to represent the logical ANDThe logical AND is used to test whether or not two statements are both true.
For two logical expressions A and B, the logical expression A & B is true only if both A and B evaluate to true.
## [1] FALSE
## [1] FALSE
## [1] TRUE
The logical operator
|
is used in R to represent the logical OR.For two Boolean expressions A and B, the Boolean expression A | B is true if at least one of A and B evaluates to true.
Note that if A and B are both true, A | B will be true; or does not mean only one of A and B is true.
## [1] TRUE
## [1] TRUE
## [1] TRUE
The logical operator ! is used to represent the logical NOT.
If the logical expression A is true, then ! A is false.
## [1] FALSE
## [1] FALSE
## [1] TRUE
- Note that we can apply logical operations to the keywords
TRUE
andFALSE
themselves:
## [1] FALSE
## [1] TRUE
## [1] FALSE
- The below table summarizes the logical operations discussed.
Operator | Meaning | Example | Result |
---|---|---|---|
! | Logical NOT | !TRUE | FALSE |
!FALSE | TRUE | ||
&& | Logical AND | FALSE & FALSE | FALSE |
TRUE & FALSE | FALSE | ||
FALSE & TRUE | FALSE | ||
TRUE & TRUE | TRUE | ||
|| | Logical OR | FALSE | FALSE | FALSE |
TRUE | FALSE | TRUE | ||
FALSE | TRUE | TRUE | ||
TRUE | TRUE | TRUE |
2.1.3 Precedence with logical operations
Operators | Meaning | Precedence |
---|---|---|
&, |, ! | Boolean operators | Low |
+, - | Addition and subtraction | |
*, /, %% | Multiplication, division, remainder | |
**, ^ | Exponentiation | |
(expressions …) | Parenthesis | High |
- Mathematical operations are generally performed before logical operations.
## [1] TRUE
## [1] TRUE
2.1.4 Abbreviating TRUE and FALSE with T and F
- You can use
T
andF
in place ofTRUE
andFALSE
- I usually do not use
T
andF
, but you will often seeT
andF
used.
- I usually do not use
## [1] TRUE
## [1] FALSE
## [1] FALSE
## [1] TRUE
- While you can use
T
andF
in place ofTRUE
andFALSE
, it is good practice to be careful when using these logical abbreviations.
T <- 2 ## T is defined as a variable
## Now T represents a vector with
T ## a number value, not TRUE
## [1] 2
## [1] FALSE
2.1.6 logical operators and vectors
You can also apply the logical operators
&
,|
,!
to two vectors.As an example, let us first define two logical vectors
x
andy
of length 4
## [1] TRUE FALSE TRUE FALSE
## [1] TRUE TRUE FALSE FALSE
Applying the logical operator
&
tox
andy
will apply an element-by-element logical and to the elements ofx
andy
.That is, running
x & y
will return the following result
- Similarly, applying the logical operator
|
tox
andy
will apply an element-by-element logical or to the elements ofx
andy
.
- Using the logical operator
!
with a vector will just return a vector where theTRUE
values have been switched toFALSE
and theFALSE
values have been switched toTRUE
:
## [1] FALSE TRUE FALSE TRUE
2.1.7 && vs. & and || vs. |
I would suggest using
&
for the logical AND operator and|
for the logical OR operator.You may sometimes see
&&
and||
being used in R code.&&
and||
can only be used for comparing vectors of length 1.- For vectors of length 1, they do the exact same thing as
&
and|
- For vectors of length 1, they do the exact same thing as
For example,
## [1] FALSE
## [1] FALSE
## [1] TRUE
## [1] TRUE
2.2 If and If-else statements
2.2.1 if statements
- In R, the form of an if statement is the following:
condition
is usually a logical expression, but could just be a logical vector of length 1 (i.e., TRUE or FALSE).If
condition
evaluates to TRUE,code_chunk1
will be executed.You actually do not have to indent the code in
code_chunk1
, but I would recommend that you do indent.The code inside {…} will be executed only if the condition of the if statement is TRUE.
## [1] "hello"
2.2.2 if statement examples
- Example 1: Running the following code will output the message in the
if
statement because the logical expressionx < y
evalutes to TRUE
## [1] "x is smaller than y"
- Example 2: Running the following code will not print out anything:
- Example 3:
## [1] "x is greater than y"
- Example 4:
## [1] "Hello"
- Example 5:
- Example 6:
- Example 7:
## [1] "Hello"
2.2.3 Single-line if statements
If the code to be executed in the if statement is short, you can write it immediately after
if(condition)
on the same line.Or, you can write the single-line statement on the line immediately below
if(condition)
## [1] 10
- This single-line if statement is the same as using:
## [1] 10
2.3 if-else statements
In many cases, you want to perform an action if a condition is true but perform another action if that condition is false.
This can be done with an if-else statement.
In R, the form of an if-else statement is the following:
As with if statements,
condition
is usually a logical expression, but could just be a logical vector (with a single element).If
condition
evaluates to TRUE,code_chunk1
will be executed.Otherwise, if condition evaluates to FALSE,
code_chunk2
will be executed.
- As an example, let’s write an if-else statement that computes the absolute value of a number.
x <- -3.2
if( x > 0 ) {
abs_x <- x # assign the variable abs_x the
# value stored in x
} else {
abs_x <- -x # assign the variable abs_x the
# negative of the value stored in x
}
abs_x # print the value stored in abs_x
## [1] 3.2
- Another if-else example:
## [1] "world"
- Another if-else example:
## [1] "Hello"
2.3.1 if-else-if chains
In many cases, a desired computation will depend on more than 2 conditions.
For these cases, you can use an if - else if - else chain of conditional statements.
The general syntax for an if - else if - else chain in R is:
if ( condition1 ) { ## If condition1 is TRUE,
code_chunk1 ## code_chunk1 will be executed.
} else if ( condition2 ) { ## If condition1 is FALSE
## and condiiton2 is TRUE,
code_chunk2 ## code_chunk2 will be executed
} else if ( condition3 ) { ## If both conditions 1 and 2 are FALSE
## and condition3 is TRUE,
code_chunk3 ## code_chunk3 will be executed
}
.
.
} else { ## If all previous conditions are FALSE,
else_chunk ## else_chunk will be executed
}
- An if-else if-else example:
x = 2
if ( x < 0 ) { ## If the condition is TRUE,
"x is negative" ## this statement will run.
} else if ( x == 0 ) {## If previous conditions are FALSE but this
"x is zero" ## is TRUE, this statement will run.
} else { ## If previous conditions are FALSE,
"x is positive" ## this statement will run.
}
## [1] "x is positive"
- Another if-else if-else example:
message <- "second"
if ( message == "first" ) {
"hello"
} else if ( message == "second" ) {
"world"
} else {
"nothing"
}
## [1] "world"
Be careful about the location of
else
in if-else if-else statementsIn R, you do not want to start a line with
else if
orelse
.For example, the following if-else statement will not run
2.3.2 Nested if-else statements
- You can certainly have if-else statements within a conditional statement.
x = 3
if ( x %% 2 == 0 ) { ## first condition
if ( x < 0) { ## second condition
"x is even and negative"
} else {
"x is even and non-negative"
}
} else if ( x < 0 ) {## this if statement is not nested
"x is odd and negative"
} else { ## not nested either
"x is odd and non-negative"
}
## [1] "x is odd and non-negative"
2.4 The ifelse function
- The
ifelse
function is a useful function that acts as a “vectorized” if-else statement.