6 Conditionals
Learning Objectives
- Understand how to use
if
andelse
statements to handle conditional programming.Suggested Readings
- Chapters 9.2 - 9.3 of “Hands-On Programming with R”, by Garrett Grolemund
Like most programming languages, R can evaluate conditional statements. A conditional statement is a switch - it tells the code which command to execute depending on a condition that is specified by the programmer.
The most prominent examples of a conditional statement is the if
statement, and the accompanying else
statement.
6.1 if
The basic format of an if
statement in R is as follows:
if ( CONDITION ) {
STATEMENT1
STATEMENT2
ETC
}
If the condition is TRUE
, then R will execute the statements contained in the curly braces, otherwise it will skip it. This schematic illustrates the idea:
Example 1
f(0)
#> ABCD
f(1)
#> AD
Example 2
Consider a simple absolute value function. Since abs()
is a built-in function, we’ll call ours absValue()
:
absValue <- function(x) {
if (x < 0) {
x = -1*x
}
return(x)
}
absValue(7) # Returns 7
#> [1] 7
absValue(-7) # Also returns 7
#> [1] 7
6.2 if else
You can extend the if
statement to include an else
statement as well, leading to the following syntax:
if ( CONDITION ) {
STATEMENT1
STATEMENT2
ETC
} else {
STATEMENT3
STATEMENT4
ETC
}
The interpretation of this version is similar. If the condition is TRUE
, then the contents of the first block of code are executed; but if it is FALSE
, then the contents of the second block of code are executed instead. The schematic illustration of an if-else construction looks like this:
Example
f(0)
#> ABCG
f(1)
#> ADEG
f(2)
#> ADFG
6.3 else if
You can also chain multiple else if
statements together for a more complex conditional statement. For example, if you’re trying to assign letter grades to a numeric test score, you can use a series of else if
statements to search for the bracket the score lies in:
getLetterGrade <- function(score) {
if (score >= 90) {
grade = "A"
} else if (score >= 80) {
grade = "B"
} else if (score >= 70) {
grade = "C"
} else if (score >= 60) {
grade = "D"
} else {
grade = "F"
}
return(grade)
}
Page sources
Some content on this page has been modified from other courses, including:
- CMU 15-112: Fundamentals of Programming, by David Kosbie & Kelly Rivers
- Danielle Navarro’s website “R for Psychological Science”