SST 301 • UNIT 2 • Statistics

Grouping, Loops & Control Structures

Topics covered: Conditional Execution, for Loops & Iteration, Jump Statements, while & repeat Loops

Looking for SST 301 Grouping, Loops & Control Structures PDF material?
Generate printable PDF revision notes, past examination papers with marking rubrics, and formula cheat sheets.
Download Course PDF Pack (.zip)

Syllabus Study Notes (Core Overview)

Free Overview Preview

1. Concept and Use Case

1.1 Conditional Execution

Conditional execution allows a program to choose between different blocks of code based on whether a logical condition evaluates to TRUE or FALSE. In R, the primary branching constructs are if, else if, and else. These are used when the outcome of a computation depends on one or more tests, such as checking whether a value exceeds a threshold, whether a matrix has a particular dimension, or whether an element satisfies a given property.

A vectorized alternative to the if/else chain is the ifelse() function. Where if/else operates on a single logical value, ifelse() applies a test element-wise across a vector and returns a result vector of the same length. This is useful when the same decision rule must be applied to every element of a data structure without writing an explicit loop.

1.2 for Loops and Iteration

A for loop repeats a block of code a fixed number of times, iterating over the elements of a sequence. In R, the sequence is typically a numeric vector, such as 1:10, or an index set used to access rows and columns of a matrix. Iteration is the fundamental mechanism for processing each element, row, or column of a data structure in turn.

Common use cases include iterating over numeric sequences to accumulate a result, indexing through matrix rows or columns to perform row-wise or column-wise operations, and batch plotting where multiple plots are produced in a single graphical layout using par(mfrow). Nested for loops — a loop inside another loop — are used when a two-dimensional traversal is required, such as visiting every element of a matrix.

1.3 Jump Statements

Jump statements alter the normal flow of a loop. R provides two such statements: break and next. The break statement terminates the innermost loop immediately, transferring control to the first statement after the loop. The next statement skips the remainder of the current iteration and proceeds to the next iteration of the loop. These statements give fine-grained control over iteration, allowing early exit when a condition is met or skipping elements that do not require processing.

1.4 while and repeat Loops

A while loop executes a block of code repeatedly as long as a specified condition remains TRUE. The condition is evaluated before each iteration, so the loop may execute zero times if the condition is initially FALSE. This is a conditional loop: its continuation depends on a logical test.

A repeat loop is an unconditional infinite loop. It executes its block repeatedly without any built-in termination condition. To exit a repeat loop, a break statement must be placed inside the loop body, typically guarded by an if condition. This pattern is useful when the termination condition is naturally evaluated at the end of the loop body rather than at the beginning.


2. Data, Syntax, and Core Concepts

2.1 Conditional Execution: if, else if, else

The if statement evaluates a logical expression. If the expression is TRUE, the associated block executes. The else if construct allows additional tests to be chained, and else provides a default block when none of the preceding conditions hold.

# if, else if, else branching
x <- 7
if (x > 10) {
 result <- "greater than 10"
} else if (x > 5) {
 result <- "greater than 5 but not greater than 10"
} else {
 result <- "5 or less"
}
result

The condition inside the parentheses must evaluate to a single logical value (TRUE or FALSE). When the condition is TRUE, the first block runs; when it is FALSE, control passes to the else if test, and so on. If all tests fail, the else block runs.

2.2 Vectorized Conditionals: ifelse()

The ifelse() function takes three arguments: a logical test vector, a value for TRUE elements, and a value for FALSE elements. It returns a vector of the same length as the test vector.

# vectorized conditional with ifelse()
scores <- c(45, 72, 88, 30, 95)
grades <- ifelse(scores >= 50, "Pass", "Fail")
grades

Here scores >= 50 produces a logical vector c(FALSE, TRUE, TRUE, FALSE, TRUE), and ifelse() returns c("Fail", "Pass", "Pass", "Fail", "Pass"). This avoids writing an explicit loop over the vector.

2.3 for Loops

The general form of a for loop is:

for (variable in sequence) {
 # body
}

The variable takes each value of sequence in turn. The sequence may be a numeric vector such as 1:5, a character vector, or any vector-like object.

# iterating over a numeric sequence
total <- 0
for (i in 1:5) {
 total <- total + i
}
total

This loop adds the integers 1 through 5, producing 15.

2.4 Indexing Through Matrix Rows and Columns

A for loop can iterate over row or column indices to process a matrix systematically.

# indexing through matrix rows
A <- matrix(1:6, nrow = 3, ncol = 2)
for (i in 1:nrow(A)) {
 row_sum <- sum(A[i, ])
 print(row_sum)
}

The expression nrow(A) returns the number of rows, and A[i, ] extracts the entire $i$-th row. Similarly, A[, j] extracts the $j$-th column, and ncol(A) returns the number of columns.

2.5 Batch Plotting with par(mfrow)

The par(mfrow) function sets the graphical parameter that controls the layout of multiple plots in a single window. The argument is a vector of two integers: the number of rows and the number of columns of the plot grid.

# batch plotting with par(mfrow)
par(mfrow = c(2, 2))
for (i in 1:4) {
 plot(1:10, (1:10)^i, main = paste("Power", i))
}

This produces four plots arranged in a $2 \times 2$ grid, each showing the sequence $1, 2, \ldots, 10$ raised to the power $i$.

2.6 Nested for Loops

A nested for loop places one loop inside another. The inner loop completes all its iterations for each single iteration of the outer loop.

# nested for loops over a matrix
A <- matrix(1:6, nrow = 3, ncol = 2)
for (i in 1:nrow(A)) {
 for (j in 1:ncol(A)) {
 A[i, j] <- A[i, j] * 2
 }
}
A

The outer loop runs over rows, and the inner loop runs over columns, so every element is visited exactly once.

2.7 Jump Statements: break and next

The break statement exits the innermost loop immediately.

# break terminates the loop
for (i in 1:10) {
 if (i == 5) {
 break
 }
 print(i)
}

This prints 1 through 4 and then stops when i reaches 5.

The next statement skips the rest of the current iteration and moves to the next one.

# next skips to the next iteration
for (i in 1:5) {
 if (i == 3) {
 next
 }
 print(i)
}

This prints 1, 2, 4, 5, skipping 3.

2.8 while Loops

A while loop tests a condition before each iteration.

# while loop with a conditional test
count <- 1
while (count <= 5) {
 print(count)
 count <- count + 1
}

The loop continues as long as count <= 5 is TRUE. When count becomes 6, the condition is FALSE and the loop terminates.

2.9 repeat Loops

A repeat loop has no built-in termination condition. It must be exited with break.

# R program to illustrate repeat loop
count <- 1
repeat {
 print(count)
 count <- count + 1
 if (count > 5) {
 break
 }
}

The loop prints 1 through 5 and then breaks when count exceeds 5. Without the break, the loop would run indefinitely.


Unlock Complete Study Notes & Exam Traps

The full guide includes formal proofs, worked exemplar calculations, high-yield exam traps, and examiner marking schemes. Continue studying this topic in Mentify Prep Studio.

Verified Examination Problems

7 verified questions in catalog

Question 1 (8 marks)

Consider the following R code:

x <- c(3, 7, 2, 9, 5)
total <- 0
for (i in 1:length(x)) {
 if (x[i] %% 2 == 0) {
 total <- total + x[i]
 } else {
 total <- total - x[i]
 }
}
print(total)

(i) Trace through the loop and determine the final value of total.

(ii) Rewrite the loop using a while loop that produces the same result.

(iii) Explain what the expression x[i] %% 2 == 0 tests and why it is used as a condition here.

Full Step-by-Step Solution & Marking Rubric Locked
View Solution in Studio →

Question 2 (10 marks)

Write an R program that uses nested for loops to construct a $4 \times 4$ matrix $M$ where the entry in row $i$ and column $j$ is given by

$$
M_{ij} = i^2 + 3j - 1.
$$

(i) Provide the complete R code using nested loops.

(ii) State the value of $M_{3,2}$ and verify it against your formula.

(iii) Explain why nested loops are appropriate for this task and how the outer and inner loops correspond to rows and columns.

Full Step-by-Step Solution & Marking Rubric Locked
View Solution in Studio →
+ 5 More Verified Exam Questions Available

Access all authentic past questions, interactive AI hint generation, and full marking rubrics in the course studio.

Unlock All Questions in Studio →
Ready to practice this topic interactively?
Generate custom exam variants, chat with the AI course tutor, and solve past papers.
Launch Interactive Study