What are Control Structures? Definition and Main Control Structures
Conditional Statements
All code we have written so far can be seen as a finite and fixed sequence of commands.
What's next?
Control structures allow us to change the flow of execution in our code. By incorporating logical conditions, they enable different lines of code to run based on the given conditions.
This approach differs from executing the same code in the same way each time, like we have done so far in this course!
Conditional statements: test one or more condition(s) and act on it or them
for
loop: execute a block of code for a fixed number of times
while
loop: execute a block of code while a given condition is true, and stops only once the condition is evaluated as false
Conditional statements: test one or more condition(s) and act on it or them
for
loop: execute a block of code for a fixed number of times
while
loop: execute a block of code while a given condition is true, and stops only once the condition is evaluated as false
Today we focus on Conditional Statements and next on Loops!
single test with if-else
multiple tests with if, else if, else
nested conditionals
ifelse()
or its tidyverse version if_else()
Download today's class materials and open the warm-up.R
script
if-else tests one condition and acts on it depending on whether the condition is TRUE or FALSE.
Syntax:
if (condition to be evaluated) { action performed when condition is TRUE} else { action performed when condition is FALSE}
if-else tests one condition and acts on it depending on whether the condition is TRUE or FALSE.
Syntax:
if (condition to be evaluated) { action performed when condition is TRUE} else { action performed when condition is FALSE}
age <- 14if (age > 16) { print("You can get a driving license")} else { print("You cannot drive")}
Example: What is the output of this code?
my_numbers <- c(3,4,5,"6",7)if (!is.numeric(my_numbers)) { print("At least one element is not numeric. Only provide numbers.")} else { print("All numeric elements")}
We can extend the basic if-else structure to test multiple conditions! How? by adding else if
statement(s) between the initial if
and the final else
Syntax:
if (condition1) { # action performed when condition 1 is TRUE action1} else if (condition2) { # action performed when condition 2 is TRUE action2} else { # action performed when conditions 1 and 2 are FALSE action3}
We can extend the basic if-else structure to test multiple conditions! How? by adding else if
statement(s) between the initial if
and the final else
Syntax:
if (condition1) { # action performed when condition 1 is TRUE action1} else if (condition2) { # action performed when condition 2 is TRUE action2} else { # action performed when conditions 1 and 2 are FALSE action3}
Conditional statements are evaluated sequentially (the order of your code matters!):
Example: check if a given number is positive, negative, or zero
x <- 0if (x > 0) { print("x is a positive number")} else if (x < 0) { print("x is a negative number")} else { print("x is zero")}
Another Example with multiple else if
statements:
# take user inputtemperature <- as.integer(readline(prompt = "Enter today's temperature in Celsius: "))# determine weather based on temperatureif (temperature >= 30) { weather <- "Hot"} else if (temperature >= 20) { weather <- "Cool"} else if (temperature >= 10) { weather <- "Breezy"} else { weather <- "Freezing!"}# printprint(weather)
Use nested if-else statements to specify conditions within conditions. What does this code do?
Example (the %% calculates the remainder from a division):
x <- 15if (x > 0) { if (x %% 2 == 0) { print("x is a positive even number") } else { print("x is a positive odd number") }} else { if (x %% 2 == 0) { print("x is a negative even number") } else { print("x is a negative odd number") }}
Same example but this checks also the condition x <- 0
:
x <- 0if (x > 0) { if (x %% 2 == 0) { print("x is a positive even number") } else { print("x is a positive odd number") }} else if (x < 0) { if (x %% 2 == 0) { print("x is a negative even number") } else { print("x is a negative odd number") }} else { print("x is zero")}
R accepts if
and else
statements, but also statements using ifelse()
. They are not the same and serve different purposes.
Syntax:
ifelse (condition to be evaluated, action performed when condition is TRUE, action performed when condition is FALSE)
Example:
y <- 3ifelse(sqrt(16) > y, sqrt(16), 0)
## [1] 4
Example: What is the output of this code?
numbers <- c(10, 6, 7)ifelse(numbers %% 2 == 1, "odd", "even")
Example: What is the output of this code?
numbers <- c(10, 6, 7)ifelse(numbers %% 2 == 1, "odd", "even")
## [1] "even" "even" "odd"
Example: What is the output of this code?
numbers <- c(10, 6, 7)ifelse(numbers %% 2 == 1, "odd", "even")
## [1] "even" "even" "odd"
Note the input here is a vector, not a single number, thus the output is also a vector: the code will evaluate each element of the vector.
This is because ifelse()
supports vectorized operations: operations directly applied on entire vectors of data, rather than looping through individual elements one-by-one.
Example: What is the output of this code?
library(tidyverse)qualify <- tibble("Athlet" = c("Noah", "Julio", "Nick", "Maria"), "Scores" = c(32, 37, 28, 30))ifelse(qualify$"Scores" > 30, "Admitted", "Rejected")
Example: What is the output of this code?
library(tidyverse)qualify <- tibble("Athlet" = c("Noah", "Julio", "Nick", "Maria"), "Scores" = c(32, 37, 28, 30))ifelse(qualify$"Scores" > 30, "Admitted", "Rejected")
## [1] "Admitted" "Admitted" "Rejected" "Rejected"
Example: use ifelse()
to recode variables in a dataframe...
The variable decisionDirection
takes four values (1 conservative, 2 liberal, 3 unspecifiable, and NA).
Recode it to take three values (0 conservative, 1 liberal, and NA for both NA and unspecifiable)
scdb_case %>% mutate(decisionDirection = ifelse( decisionDirection == 3, # condition to be evaluated NA, # if true, do NA decisionDirection - 1 # if false, subtract one to value ))
Similarly to other functions we have seen, there is also a dplyr
version of the base R ifelse()
function and it is called if_else()
. They follow the same logic, but the latter is better to use with the tidyverse
Documentation here:https://dplyr.tidyverse.org/reference/if_else.html
Compare the two!
Download today's class materials from the website
What are Control Structures? Definition and Main Control Structures
Conditional Statements
Keyboard shortcuts
↑, ←, Pg Up, k | Go to previous slide |
↓, →, Pg Dn, Space, j | Go to next slide |
Home | Go to first slide |
End | Go to last slide |
Number + Return | Go to specific slide |
b / m / f | Toggle blackout / mirrored / fullscreen mode |
c | Clone slideshow |
p | Toggle presenter mode |
t | Restart the presentation timer |
?, h | Toggle this help |
Esc | Back to slideshow |