+ - 0:00:00
Notes for current slide
Notes for next slide

MACS 30500 LECTURE 9

Topics: Intro to Control Structures. Conditional Statements.

1 / 19

Agenda

  • What are Control Structures? Definition and Main Control Structures

  • Conditional Statements

2 / 19

What are Control Structures?

3 / 19

Control Structures: Definition

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!

4 / 19

Main Control Structures

  • 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

5 / 19

Main Control Structures

  • 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!

5 / 19

Conditional Statements

  • 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

6 / 19

if-else

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
}
7 / 19

if-else

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 <- 14
if (age > 16) {
print("You can get a driving license")
} else {
print("You cannot drive")
}
7 / 19

if-else

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")
}
8 / 19

if, else if, else

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
}
9 / 19

if, else if, else

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!):

  • conditions are checked one-by-one in the order they are written
  • once R finds a TRUE condition, it stops, and the remaining conditions are not evaluated
9 / 19

if, else if, else

Example: check if a given number is positive, negative, or zero

x <- 0
if (x > 0) {
print("x is a positive number")
} else if (x < 0) {
print("x is a negative number")
} else {
print("x is zero")
}
10 / 19

if, else if, else

Another Example with multiple else if statements:

# take user input
temperature <- as.integer(readline(prompt = "Enter today's temperature in Celsius: "))
# determine weather based on temperature
if (temperature >= 30) {
weather <- "Hot"
} else if (temperature >= 20) {
weather <- "Cool"
} else if (temperature >= 10) {
weather <- "Breezy"
} else {
weather <- "Freezing!"
}
# print
print(weather)
11 / 19

Nested if-else

Use nested if-else statements to specify conditions within conditions. What does this code do?

Example (the %% calculates the remainder from a division):

x <- 15
if (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")
}
}
12 / 19

Nested if-else

Same example but this checks also the condition x <- 0:

x <- 0
if (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")
}
13 / 19

ifelse()

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 <- 3
ifelse(sqrt(16) > y,
sqrt(16),
0)
## [1] 4
14 / 19

ifelse()

Example: What is the output of this code?

numbers <- c(10, 6, 7)
ifelse(numbers %% 2 == 1,
"odd",
"even")
15 / 19

ifelse()

Example: What is the output of this code?

numbers <- c(10, 6, 7)
ifelse(numbers %% 2 == 1,
"odd",
"even")
## [1] "even" "even" "odd"
15 / 19

ifelse()

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.

15 / 19

ifelse()

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")
16 / 19

ifelse()

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"
16 / 19

ifelse()

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
))
17 / 19

if_else()

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!

18 / 19

Practice writing conditional statements

Download today's class materials from the website

19 / 19

Agenda

  • What are Control Structures? Definition and Main Control Structures

  • Conditional Statements

2 / 19
Paused

Help

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