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

STA 326 2.0 Programming and Data Analysis with R

🔩 Control Structures in R

Dr Thiyanga Talagala

1

Today's menu

Control structures (loops/ conditional executions)

if, else

for

while

repeat

break

next

switch

2

Conditional executions control the flow of the execution.

3

Draw a star on star-shaped cookies and draw a heart on heart-shaped cookies.

4

if-else

Draw a star on star-shaped cookies and draw a heart on heart-shaped cookies.

5

if-else

if (condition) {
# do something
} else {
# do something else
}

Example

test_even_odd <- function(x){
if (x %% 2 == 0){
print("even number")
} else {
print("odd number")
}
}
test_even_odd(5)
[1] "odd number"
test_even_odd(6)
[1] "even number"
6

ifelse: vectorization with ifelse

ifelse(condition, TRUE condition output, FALSE condition output)

Example

test_even_odd_v2 <- function(x){
ifelse(x %% 2 == 0, "even number", "odd number")
}
test_even_odd_v2(5)
FALSE [1] "odd number"
test_even_odd_v2(c(1,6))
FALSE [1] "odd number" "even number"
7

Difference between if, else and ifelse

if, else

test_even_odd <- function(x){
if (x %% 2 == 0) {
print("even number")
} else {
print("odd number")
}
}
test_even_odd(5)
FALSE [1] "odd number"
test_even_odd(c(1,6))
# returns an error

ifelse

test_even_odd_v2 <- function(x){
ifelse (x %% 2 == 0, "even number", "odd number")
}
test_even_odd_v2(5)
FALSE [1] "odd number"
test_even_odd_v2(c(1,6))
FALSE [1] "odd number" "even number"
8

Nested if-else

  • Multiple conditions
grade_marks <- function(marks){
if (marks < 20) {
"D"
} else if (marks <= 50) {
"C"
} else if (marks <= 60) {
"B"
} else {
"A"
}
}
grade_marks(75)
[1] "A"
9

Your turn

10

R for Data Science-Exercises 19.4.4 - Q2

Help:

lubridate::now() and lubridate::hour()

10:00
11

if

check.negative <- function(x){
if (x < 0 ) {
print("X is negative")
}
}
check.negative(-10)
[1] "X is negative"
check.negative(10)
12

For the first 50 cookies, fill the center of cookies with jam.

13

for

For the first 50 cookies, fill the center of cookies with jam.

14

for loop

  • execute a block of code a specific number of times or until the end of a sequence.
for (i in 1:5) {
print(i*100)
}
[1] 100
[1] 200
[1] 300
[1] 400
[1] 500
15
continents <- c("Asia", "EU", "AUS", "NA", "SA", "Africa")
for (i in 1:4) {
print(continents[i])
}
[1] "Asia"
[1] "EU"
[1] "AUS"
[1] "NA"
for (i in 1:4) print(continents[i])
[1] "Asia"
[1] "EU"
[1] "AUS"
[1] "NA"
for (i in seq(continents)) {
print(continents[i])
}
[1] "Asia"
[1] "EU"
[1] "AUS"
[1] "NA"
[1] "SA"
[1] "Africa"
16

Your turn

17

Write a for loop that iterates over the numbers 1 to 4 and prints the squared of each number using print().

03:00
18

For the first 50 cookies, draw a star on star-shaped cookies and draw a heart on heart-shaped cookies.

19

nested loops

For the first 50 cookies, draw a star on star-shaped cookies and draw a heart on heart-shaped cookies.

20

Nested loops

a <- 1:10
testfun <- function(x){
for (x in 1:5) {
if (x %% 2 == 0) {
print("even number")
} else {
print("odd number")
}
}}
testfun(a)
[1] "odd number"
[1] "even number"
[1] "odd number"
[1] "even number"
[1] "odd number"
21

Nested loops

mat <- matrix(1:6, ncol=2)
mat
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
for (i in 1:3) {
for (j in 1:2) {
print(mat[i, j])
}
}
[1] 1
[1] 4
[1] 2
[1] 5
[1] 3
[1] 6
22

Your turn

23

Write a function to count the number of even numbers in a vector.

08:00
24

Taste the cookies one by one until you find the star-shaped cookie.

25

while

Taste the cookies one by one until you find the star-shaped cookie.

26

while

i <- 1 # initial value
while (i != 10) {
print(i)
i <- i + 1 # increment
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
i <- 1 # initial value
while (i < 10) {
print(i)
i <- i + 1 # increment
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
27

Your turn

28

Can you guess the output?

i <- 1 # initial value
while (i == 10) {
print(i)
i <- i + 1 # increment
}
01:00
29

Your turn

30

Generate the first n numbers of the Fibonacci Sequence using while loop.

0 1 1 2 3 5 ...

04:00
31

Taste the cookies one by one until you find the strawberry flavoured cookie.

32

repeat-break

Taste the cookies one by one until you find the strawberry flavoured cookie.

33

repeat and break

  • Iterate over a block of code multiple number of times.

  • No condition check in repeat loop to exit the loop.

  • The only way to exit a repeat loop is to call break.

34

repeat and break

Example 1

x <- 5
repeat {
print(x)
x = x+1
if (x == 10){
break
}
}
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
35

repeat and break

Example 1

x <- 5
repeat {
print(x)
x = x+1
if (x == 10){
break
}
}
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9

Example 2

set.seed(1)
repeat {
x<-runif(1, 5, 10)
print(x)
if(x < 6.1){
break
}
}
[1] 6.327543
[1] 6.860619
[1] 7.864267
[1] 9.541039
[1] 6.00841
36

Your turn

  1. Write a function to print random numbers from the standard normal distribution but stops (breaks) if you get a number bigger than 1.

  2. Using next adapt the loop from last exercise so that doesn’t print negative numbers.

37

Skip cracked muffins and decorate the rest.

38

next

Skip cracked muffins and decorate the rest.

39

next

for(i in 1:10) {
if(i <= 5) {
next # Skip the first 5 iterations
}
print(i)
}
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
40

Green base - roses, Red - small dots, Pink - stars, ...

41

switch

Green base - roses, Red - small dots, etc..

42

switch

When you want a function to do different things in different circumstances, then the switch function can be useful.

feelings <- c("sad", "afraid")
for (i in feelings){
print(
switch(i,
happy = "I am glad you are happy",
afraid = "There is nothing to fear",
sad = "Cheer up",
angry = "Calm down now"
))
}
[1] "Cheer up"
[1] "There is nothing to fear"
43

Single element - working

x <- "a"
v <- switch(x, "a" = "apple",
"b" = "banana",
"c" = "cherry")
v
[1] "apple"

Multiple elements - not working

switch(c("a", "b"), "a" = "apple", # not working
"b" = "banana",
"c" = "cherry")

Multiple element - use for loop

vect <- c("a", "b")
for(i in seq(vect)){
print(switch(i, "a" = "apple",
"b" = "banana",
"c" = "cherry"))
}
## [1] "apple"
## [1] "banana"
44

Thank you!

Slides available at: hellor.netlify.app

All rights reserved by Thiyanga S. Talagala

45

Today's menu

Control structures (loops/ conditional executions)

if, else

for

while

repeat

break

next

switch

2
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
Alt + fFit Slides to Screen
Esc Back to slideshow