BSTA 3152 STATISTICAL PROGRAMMING Control Structures
BSTA 3152 Statistical Programming: LECTURE 2
eDon Symon
2024-10-22
CONTROL STURCTURES IN R
Control structures in R allow you to control the flow of execution of a series of R expressions.
Basically, control structures allow you to put some “logic” into your R code, rather than just always executing
the same R code every time.
Control structures allow you to respond to inputs or to features of the data and execute different R expressions
accordingly.
Commonly used control structures are
1. if and else: testing a condition and acting on it
2. for: execute a loop a fixed number of times
3. nested loops
4. while: execute a condition while a condition is true
5. repeat: execute an infinite loop
6. break: break the execution of a loop
7. next: skip an iteration of a loop
8. return:
Most control structures are not used in interactive sessions, but rather when writing functions or longer
expressions. However, these constructs do not have to be used in functions and it’s a good idea to become
familiar with them before we delve into functions.
Prepared by Symon K. Matonyo Lecture 1
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
1. if Condition in R
This task is carried out only if this condition is returned as TRUE. R makes it even easier: You can drop the
word then and specify your choice in an if statement.
Syntax:
if (test_expression) {
statement
}
Example 1:
# Example 1
values <- 1:10
if (sample(values,1) <= 10)
print(paste(values, "is less than or equal to 10"))
Example 2:
# Example 2
x <- 100
if(x > 10){
print(paste(x, "is greater than 10"))
}
2. if-else Condition in R
An if. . . else statement contains the same elements as an if statement (see the preceding section), with some
extra elements:
-The keyword else, placed after the first code block.
-The second block of code, contained within braces, that has to be carried out, only if the result of the
condition in the if() statement is FALSE.
Syntax:
if (test_expression) {
statement
} else {
Prepared by Symon K. Matonyo Lecture 2
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
statement
}
Example 1:
# Example 1
val1 = 10 #Creating our first variable val1
val2 = 5 #Creating second variable val2
if (val1 > val2){ #Executing Conditional Statement based on the comparison
print("Value 1 is greater than Value 2")
} else if (val1 < val2){
print("Value 1 is less than Value 2")
}
Example 2:
# Example 2
## evaluating if a condition is met and returning a specific value if true
x <- 5
if(x > 3) {
y <- 10
} else {
y <- 0
}
Example 3:
# Example 3
x <- 5
# Check value is less than or greater than 10
if(x > 10){
print(paste(x, "is greater than 10"))
}else{
print(paste(x, "is less than 10"))
}
Example:
For the data on ages of people given as follows 12, 18, 32, 2,4. If a person is aged less than 18 they are
classified as minor otherwise voter.
ages <- c(12,18,32,2,4)
ifelse(ages < 18, "Minor", "Voter")
## [1] "Minor" "Voter" "Voter" "Minor" "Minor"
Example 4:
After an exam, the possibilities are as follows: if you have less than 12, the comment is “passable”, if you are
between 12 and 14 the comment is “Good”. If you have above 14 the comment is “Very Good”. Write an R
code that classifies a student who scores 16 in an exam
#Example 4
# the exam score
exam = 16
ifelse(exam < 12, "Passable", ifelse(12 < exam & exam <14, "Good",
ifelse(exam > 14, "Very Good")))
# code two
Prepared by Symon K. Matonyo Lecture 3
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
if(exam < 12){
print("Passable")
} else if(12 < exam & exam < 14){
print("Good")
}else{
print("Very Good")
}
we can use if else to have a Vector function that returns a vector of the same length as condition formed as
follows : for each element TRUE of condition we choose the corresponding element of [Link] and for
each element FALSE we choose the corresponding element of [Link].
Example 5:
For the data on ages of people given as follows 12, 18, 32, 2,4. If a person is aged less than 18 they are
classified as minor otherwise voter.
# Example 5
ages <- c(12,18,32,2,4)
ifelse(ages < 18, "Minor", "Voter")
3. for Loop
A loop is a sequence of instructions that is repeated until a certain condition is reached. for, while and repeat,
with the additional clauses break and next are used to construct loops.
The three key aspects of a loop are:
a. Loop Object: The object that will change for each iteration of the loop. This is usually a letter like i or an
object with subscript like column.i or participant.i. You can use any object name that you want for the index.
b. Loop Vector: A vector specifying all values that the loop object will take over the loop. You can specify
the values any way you’d like (as long as it’s a vector). If you’re running a loop over numbers, you’ll probably
want to use a:b or seq(). However, if you want to run a loop over a few specific values, you can just use the
c() function to type the values manually.
c. Loop Code: The code that will be executed for all values in the loop vector. You can write any R code
you’d like in the loop code - from plotting to analyses.
A flow chart of the for loop:
Prepared by Symon K. Matonyo Lecture 4
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
Prepared by Symon K. Matonyo Lecture 5
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
Syntax:
for(value in vector){
statements
....
....
}
Example 1:
# Example 1
values <- c(1,2,3,4,5)
for(id in 1:5){
print(values[id])
}
Example 2:
# Example 2
x <- letters[4:10]
for(i in x){
print(i)
}
Example 3:
#Example 3
x <- letters[4:10]
for(i in x){
print(i)
}
Example 4:
#Example 4
x <- c("a", "b", "c", "d")
for(i in 1:4) {
## Print out each element of 'x'
print(x[i])
}
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
# Output
The seq_along() function is commonly used in conjunction with for loops in order to generate an integer
sequence based on the length of an object (in this case, the object x).
Example 5:
#Example 5
## Generate a sequence based on length of 'x'
for(i in seq_along(x)) {
print(x[i])
Prepared by Symon K. Matonyo Lecture 6
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
# Output
Example 6:
# Example program using a for loop
numbers <- c(1, 2, 3, 4, 5)
for (num in numbers) {
print(paste("The square of", num, "is", numˆ2))
}
## [1] "The square of 1 is 1"
## [1] "The square of 2 is 4"
## [1] "The square of 3 is 9"
## [1] "The square of 4 is 16"
## [1] "The square of 5 is 25"
4. Nested Loop
R programming language allows using one loop inside another loop. In loop nesting, we can put any type of
loop inside of any other type of loop.
It is similar to the standard for loop, which makes it easy to convert for loop to a foreach loop. Unlike many
parallel programming packages for R, foreach doesn’t require the body of for loop to be turned into a function.
We can call this a nesting operator because it is used to create nested foreach loops.
Example 1:
# Example 1
# R Program to demonstrate the use of
# nested for loop
for (i in 1:3)
{
for (j in 1:i)
{
print(i * j)
}
}
## [1] 1
## [1] 2
## [1] 4
## [1] 3
## [1] 6
## [1] 9
Example: A for loop over a matrix, a matrix has two dimensions rows and columns. To iterate over a
matrix, we have to define two for loop, namely one for the rows and the other for the column.
# Create a matrix
mat <- matrix(data = seq(10, 20, by=1), nrow = 6, ncol =2)
## Warning in matrix(data = seq(10, 20, by = 1), nrow = 6, ncol = 2): data length
Prepared by Symon K. Matonyo Lecture 7
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
## [11] is not a sub-multiple or multiple of the number of rows [6]
# Create the loop with r and c to iterate over the matrix
for (r in 1:nrow(mat))
for (c in 1:ncol(mat))
print(paste("Row", r, "and column",c, "has value", mat[r,c]))
## [1] "Row 1 and column 1 has value 10"
## [1] "Row 1 and column 2 has value 16"
## [1] "Row 2 and column 1 has value 11"
## [1] "Row 2 and column 2 has value 17"
## [1] "Row 3 and column 1 has value 12"
## [1] "Row 3 and column 2 has value 18"
## [1] "Row 4 and column 1 has value 13"
## [1] "Row 4 and column 2 has value 19"
## [1] "Row 5 and column 1 has value 14"
## [1] "Row 5 and column 2 has value 20"
## [1] "Row 6 and column 1 has value 15"
## [1] "Row 6 and column 2 has value 10"
Example:
# Example 2
# Defining matrix
m <- matrix(2:15, 2)
m
for (r in seq(nrow(m))) {
for (c in seq(ncol(m))) {
print(m[r, c])
}
}
Example:
One of the best uses of a loop is to create multiple graphs quickly and easily. Let’s use a loop to create 4
plots representing data from an exam containing 4 questions.
The data are represented in a matrix with 100 rows (representing 100 different people), and 4 columns
representing scores on the different questions.
The data are stored in the yarrr package in an object called examscores.
Now, we’ll loop over the columns and create a histogram of the data in each column. First, I’ll set up a 2 x 2
plotting space with par(mfrow())
library(yarrr)
## Loading required package: jpeg
## Loading required package: BayesFactor
## Loading required package: coda
## Loading required package: Matrix
## ************
## Welcome to BayesFactor 0.9.12-4.7. If you have questions, please contact Richard Morey (richarddmorey
##
## Type BFManual() to open the manual.
## ************
Prepared by Symon K. Matonyo Lecture 8
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
## Loading required package: circlize
## ========================================
## circlize version 0.4.16
## CRAN page: [Link]
## Github page: [Link]
## Documentation: [Link]
##
## If you use it in published research, please cite:
## Gu, Z. circlize implements and enhances circular visualization
## in R. Bioinformatics 2014.
##
## This message can be suppressed by:
## suppressPackageStartupMessages(library(circlize))
## ========================================
## yarrr v0.1.5. Citation info at citation('yarrr'). Package guide at [Link]()
## Email me at [Link]@[Link]
# Set up a 2 x 2 plotting space
par(mfrow = c(2, 2))
# Create the [Link] (all the columns)
[Link] <- 1:4
for (i in [Link]) { # Loop over [Link]
# store data in column.i as x
x <- examscores[,i]
# Plot histogram of x
hist(x,
main = paste("Question", i),
xlab = "Scores",
xlim = c(0, 100))
}
Prepared by Symon K. Matonyo Lecture 9
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
20
Question 1 Question 2
40
Frequency
Frequency
10
20
0
0
0 20 40 60 80 100 0 20 40 60 80 100
Scores Scores
Question 3 Question 4
25
30
Frequency
Frequency
15
10
0
0
0 20 40 60 80 100 0 20 40 60 80 100
Scores Scores
Example:
Let’s do an example with the examscores dataframe. We’ll use a loop to calculate how many students failed
each of the 4 exams – where failing is a score less than 50. To do this, we will start by creating an NA vector
called [Link]. This will be a container object that we’ll update later with the loop.
# Create a container object of 4 NA values
[Link] <- rep(NA, 4)
for(i in 1:4) { # Loop over columns 1 through 4
# Get the scores for the ith column
x <- examscores[,i]
# Calculate the percent of failures
failures.i <- mean(x < 50)
# Assign result to the ith value of [Link]
[Link][i] <- failures.i
}
[Link]
## [1] 0.50 1.00 0.03 0.97
Example:_ Once an exam is done the classification criteria of grades in the university is as follows if a
student scores above 70 the score is A,60-69 B, 50-59 C, 40-49 D and below 40 E. The following are scores of
students in a test. Write a code in R that classifies the grades of each student.
# Create a dataframe with student numbers and scores
student_data <- [Link](
Student = 1:12,
Score = c(34, 56, 78, 59, 60, 45, 79, 32, 12, 78, 89, 67)
)
Prepared by Symon K. Matonyo Lecture 10
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
# Display the table using knitr::kable
knitr::kable(
student_data,
[Link] = c("Student", "Score"),
caption = "Table of Student Scores"
)
Table 1: Table of Student Scores
Student Score
1 34
2 56
3 78
4 59
5 60
6 45
7 79
8 32
9 12
10 78
11 89
12 67
Student <- 1:12
Maths <- c(34,56,78,59,60,45,79,32,12,78,89,67)
English <- c(78,90,34,45,32,21,12,56,67,78,98,65)
Mydata <- [Link](Student, Maths, English)
# using a loop
for(i in 2:ncol(Mydata)){
x <- Mydata[,i]
Mydata[,i] <- ifelse(x >=70, "A", ifelse(x >=60 & x < 70, "B", ifelse(x >=50 & x < 60,
"C", ifelse(x >=40
& x < 50,"D", "E"))))
}
#Without using for loop
Mydata$Grade_Maths <- ifelse(Maths >=70, "A", ifelse(Maths >=60 & Maths < 70, "B",
ifelse(Maths >=50 & Maths < 60,
"C", ifelse(Maths >=40
& Maths < 50,"D", "E"))))
Mydata$Grade_Eng <- ifelse(English >=70, "A", ifelse(English >=60 & Maths < 70, "B",
ifelse(English >=50 & English < 60,
"C", ifelse(English >=40
& English < 50,"D", "E"))))
5. While Loop
The while loop is used to repeatedly execute a block of code as long as a specified condition remains TRUE.
Be cautious when using while loops to avoid infinite loops.
The flow chart:
Prepared by Symon K. Matonyo Lecture 11
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
Syntax:
while (test_expression)
{
statement
}
Example 1:
# Example 1
# R Program to demonstrate the use of while loop
val = 2.987
while(val <= 4.987) {
val = val + 0.987
print(c(val,val-2,val-1))
}
Example 2:
# Example 2
i <- 1
while (i < 6) {
print(i)
i <- i + 1
}
Example 3:
# Example 3
x<-0;
while (x < 10)
{
x<- x+4;
print (x);
}
Example:
count <- 1
while (count <= 5) {
print(paste("Count is", count))
count <- count + 1
}
Prepared by Symon K. Matonyo Lecture 12
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
## [1] "Count is 1"
## [1] "Count is 2"
## [1] "Count is 3"
## [1] "Count is 4"
## [1] "Count is 5"
6. repeat and break Statements
6.1 Break
We use break statement inside a loop (repeat, for, while) to stop the iterations and flow the control
outside of the loop. While in a nested looping situation, where there is a loop inside another loop, this
statement exits from the innermost loop that is being evaluated.
Example:
x<-0;
while (x < 10)
{
x <- x + 4;
print (x);
if(x == 8)
{
break;
}
}
## [1] 4
## [1] 8
Example:
values = 1:10
for (id in values){
if (id == 2){
break
}
print(id)
}
## [1] 1
6.2 Repeat
A repeat loop is used to iterate over a block of code, multiple numbers of times. There is no condition check
in a repeat loop to exit the loop. We ourselves put a condition explicitly inside the body of the loop and use
the break statement to exit the loop. Failing to do so will result in an infinite loop.
a. First, we have to initialize our variables than it will enter into the Repeat loop.
b. This loop will execute the group of statements inside the loop.
c. After that, we have to use any expression inside the loop to exit.
d. It will check for the condition. It will execute a break statement to exit from the loop
e. If the condition is true.
Prepared by Symon K. Matonyo Lecture 13
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
f. The statements inside the repeat loop will be executed again if the condition is false
The flow chart:
Syntax:
repeat {
# simulations; generate some value have an expectation if within some range,
# then exit the loop
if ((value - expectation) <= threshold) {
break
}
}
Example:
# R Program to demonstrate the use of
# break in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
if (i == 0)
Prepared by Symon K. Matonyo Lecture 14
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
{
break
}
print(i)
}
## [1] 3
## [1] 6
## [1] 23
## [1] 19
Example:
# Example program using a repeat loop
count <- 1
repeat {
print(paste("Count is", count))
count <- count + 1
if (count > 5) {
break
}
}
## [1] "Count is 1"
## [1] "Count is 2"
## [1] "Count is 3"
## [1] "Count is 4"
## [1] "Count is 5"
Example:
# Example program using a repeat loop
count <- 1
repeat {
print(paste("Count is", count))
count <- count + 1
if (count > 5) {
break
}
}
## [1] "Count is 1"
## [1] "Count is 2"
## [1] "Count is 3"
## [1] "Count is 4"
## [1] "Count is 5"
Example:
result <- c("Hello World")
i <- 1
# test expression
repeat {
print(result)
# update expression
i <- i + 1
# Breaking condition
if(i >5) {
Prepared by Symon K. Matonyo Lecture 15
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
break
}}
Example:
# R Repeat Loop statement Example
a = 1
repeat {
# starting of repeat statements block
print(a)
a = a+1
# ending of repeat statements block
if(a>6){ # breaking condition
break
}
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
7. next Statement
next jumps to the next cycle without completing a particular iteration. In fact, it jumps to the evaluation of
the condition holding the current loop. Next statement enables to skip the current iteration of a loop without
terminating it.
It is used to skip the current iteration without executing the further statements and continues the next
iteration cycle without terminating the loop.
Example
# Defining vector
x <- 1:10
# Print even numbers
for(i in x){
if(i%%2 != 0){
next #Jumps to next loop
}
print(i)
}
## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
Example:
# Example program using the next statement
numbers <- 1:5
for (num in numbers) {
if (num == 3) {
Prepared by Symon K. Matonyo Lecture 16
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
next # Skip the iteration when num is 3
}
print(num)
}
## [1] 1
## [1] 2
## [1] 4
## [1] 5
Example:
x = 1: 4
for (i in x) {
if (i == 2) {
next
}
print(i)
}
## [1] 1
## [1] 3
## [1] 4
Example:
# R Program to demonstrate the use of
# next in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
if (i == 0)
{
next
}
print(i)
}
## [1] 3
## [1] 6
## [1] 23
## [1] 19
## [1] 21
8. Control Structures for Function Execution
8.1 switch Statement
The switch statement is used to select and execute one of several blocks of code based on the value of an
expression.
Syntax:
switch(expr, case1, case2, ..., caseN)
Example:
# Example program using the switch statement
day <- "Monday"
message <- switch(day,
Prepared by Symon K. Matonyo Lecture 17
BSTA 3152 STATISTICAL PROGRAMMING Control Structures
"Monday" = "It's the start of the workweek.",
"Tuesday" = "Another workday.",
"Wednesday" = "Midweek!",
"Thursday" = "Almost there!",
"Friday" = "Endweek",
"Saturday" = "Weekend!",
"Sunday" = "Weekend!"
)
print(message)
## [1] "It's the start of the workweek."
9. Control Structures for Function Execution
9.1 return Statement
Many times, we will require some functions to do processing and return back the result. This is accomplished
with the return() statement in R.
Syntax:
return(expression)
Example:
check <- function(x) {
if (x > 0) {
result <- "Positive"
} else if (x < 0) {
result <- "Negative"
} else {
result <- "Zero"
}
return(result) ## use of return
}
9.2 Function Recursion
Function recursion is a technique in which a function calls itself to solve a problem. This can be a powerful
way to solve complex problems that can be broken down into simpler sub-problems.
Example:
# Example program demonstrating function recursion
factorial <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
result <- factorial(5)
print(result)
## [1] 120
Prepared by Symon K. Matonyo Lecture 18