<- function(x) {
f cat("A")
if (x == 0) {
cat("B")
cat("C")
}cat("D")
}
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()
:
<- function(x) {
absValue if (x < 0) {
= -1*x
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
<- function(x) {
f cat("A")
if (x == 0) {
cat("B")
cat("C")
}else {
cat("D")
if (x == 1) {
cat("E")
else {
} cat("F")
}
}cat("G")
}
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:
<- function(score) {
getLetterGrade if (score >= 90) {
= "A"
grade else if (score >= 80) {
} = "B"
grade else if (score >= 70) {
} = "C"
grade else if (score >= 60) {
} = "D"
grade else {
} = "F"
grade
}return(grade)
}
cat("103 -->", getLetterGrade(103))
#> 103 --> A
cat(" 88 -->", getLetterGrade(88))
#> 88 --> B
cat(" 70 -->", getLetterGrade(70))
#> 70 --> C
cat(" 61 -->", getLetterGrade(61))
#> 61 --> D
cat(" 22 -->", getLetterGrade(22))
#> 22 --> F
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”