# ============================================================
# ACCA7022 – Advanced Statistical Programming
# Control Structures and Functions in R
# Complete Activities Script
# ============================================================
# ============================================================
# ACTIVITY 1: Classify numbers as positive, negative, or zero
# ============================================================
cat("\n========== ACTIVITY 1: Classify Numbers ==========\n")
# Function to classify a single number
classify_number <- function(x) {
if (x > 0) {
return("positive")
} else if (x < 0) {
return("negative")
} else {
return("zero")
}
}
# Test with different numbers
test_numbers <- c(-5, 0, 10, -3.5, 7, 0)
cat("Testing number classification:\n")
for (num in test_numbers) {
result <- classify_number(num)
cat("Number", num, "is", result, "\n")
}
# ============================================================
# ACTIVITY 2: Use a loop to sum numbers from 1 to 100
# ============================================================
cat("\n========== ACTIVITY 2: Sum Numbers 1 to 100 ==========\n")
# Method 1: Using a FOR loop
sum_for <- 0
for (i in 1:100) {
sum_for <- sum_for + i
}
cat("Sum using FOR loop:", sum_for, "\n")
# Method 2: Using a WHILE loop
sum_while <- 0
counter <- 1
while (counter <= 100) {
sum_while <- sum_while + counter
counter <- counter + 1
}
cat("Sum using WHILE loop:", sum_while, "\n")
# Method 3: Using vectorised function (for comparison)
sum_vectorised <- sum(1:100)
cat("Sum using vectorised sum():", sum_vectorised, "\n")
# ============================================================
# ACTIVITY 3: Generate random numbers until one is > 0.9
# ============================================================
cat("\n========== ACTIVITY 3: Repeat Loop with Break ==========\n")
set.seed(123)  # For reproducibility (optional - remove for true randomness)
count <- 0
repeat {
random_num <- runif(1)  # Generate one random number between 0 and 1
count <- count + 1
cat("Attempt", count, ": Random number =", round(random_num, 4), "\n")
if (random_num > 0.9) {
cat("Found a number greater than 0.9! Stopping.\n")
break
}
}
cat("Total attempts needed:", count, "\n")
# ============================================================
# ACTIVITY 4: Rewrite a loop using vectorisation
# ============================================================
cat("\n========== ACTIVITY 4: Vectorisation ==========\n")
# Example: Square all numbers from 1 to 10
# Method 1: Using a loop
cat("Using a loop:\n")
squared_loop <- c()
for (i in 1:10) {
squared_loop <- c(squared_loop, i^2)
}
print(squared_loop)
# Method 2: Using vectorisation (preferred - faster and cleaner)
cat("\nUsing vectorisation:\n")
squared_vector <- (1:10)^2
print(squared_vector)
# Another example: Calculate mean of multiple vectors
cat("\nAnother vectorisation example - applying function to list:\n")
data_list <- list(a = 1:5, b = 6:10, c = 11:15)
# Loop method
means_loop <- c()
for (vec in data_list) {
means_loop <- c(means_loop, mean(vec))
}
cat("Means using loop:", means_loop, "\n")
# Vectorised method using sapply
means_vectorised <- sapply(data_list, mean)
cat("Means using sapply:", means_vectorised, "\n")
# ============================================================
# F-1: BASIC FUNCTIONS (from F-1-BasicFunctions.R)
# ============================================================
cat("\n========== F-1: BASIC FUNCTIONS ==========\n")
# Triple - pass by value
triple <- function(x) {
x <- x * 3
x
}
# Test the function
a <- 5
cat("triple(5) =", triple(a), "\n")
cat("Original a =", a, "(unchanged)\n")
b <- c(2.1, 5.3, 7.9)
cat("triple(c(2.1, 5.3, 7.9)) =", triple(b), "\n")
c_bool <- c(TRUE, FALSE, TRUE)
cat("triple(c(TRUE, FALSE, TRUE)) =", triple(c_bool), "\n")
# Note: triple(c("A","B","C")) would fail - R can't do maths with strings
# ============================================================
# F-2: EXERCISE 1 - Three ways to calculate mean
# ============================================================
cat("\n========== F-2: EXERCISE 1 - Mean Functions ==========\n")
# Function 1: Using built-in mean()
mean_mean <- function(x) {
out <- mean(x)
out
}
# Function 2: Using a loop
mean_loop <- function(x) {
running_total <- 0
element_total <- 0
for (i in x) {
running_total <- running_total + i
element_total <- element_total + 1
}
out <- running_total / element_total
out
}
# Function 3: Using vector functions
mean_function <- function(x) {
out <- sum(x) / length(x)
out
}
# Test vectors
int_test <- 1:5
float_test <- c(1.2, 2.5, 3.5, 4.5, 5.5)
cat("Testing with integers 1:5:\n")
cat("  mean_mean:", mean_mean(int_test), "\n")
cat("  mean_loop:", mean_loop(int_test), "\n")
cat("  mean_function:", mean_function(int_test), "\n")
cat("\nTesting with floats c(1.2, 2.5, 3.5, 4.5, 5.5):\n")
cat("  mean_mean:", mean_mean(float_test), "\n")
cat("  mean_loop:", mean_loop(float_test), "\n")
cat("  mean_function:", mean_function(float_test), "\n")
# ============================================================
# F-3: MULTIPLE PARAMETERS
# ============================================================
cat("\n========== F-3: MULTIPLE PARAMETERS ==========\n")
# Function raise(x,y) - raise x to the power y
raise <- function(x, y) x^y
# Function echostring(n, string)
echostring <- function(n, string) {
return_vector <- NA
for (i in 1:length(string)) {
for (j in 1:n) {
return_vector <- c(return_vector, string[i])
}
}
return(return_vector[-1])
}
# Test raise
cat("raise(2,3) =", raise(2, 3), "\n")
a <- c(2, 3)
cat("raise(a[1], a[2]) with a=c(2,3):", raise(a[1], a[2]), "\n")
b <- c(3, 4)
cat("raise(c(2,3), c(3,4)) =", raise(a, b), "\n")
# Test echostring
cat("\nechostring(3, 'Echo...'):\n")
print(echostring(3, "Echo..."))
cat("\nechostring(3, c('A string', 'Another string')):\n")
print(echostring(3, c("A string", "Another string")))
# ============================================================
# F-4: EXERCISE 2 - Functions calling functions
# ============================================================
cat("\n========== F-4: EXERCISE 2 - Functions in Functions ==========\n")
# Function build_range(x,y,size)
build_range <- function(x, y, size) {
outvector <- seq(x, y, by = size)
return(outvector)
}
# Function print_squares(v, limit)
print_squares <- function(v, limit) {
for (i in v) {
if (i^2 <= limit) print(i^2)
}
}
# Function print_limit(x,y,size,limit)
print_limit <- function(x, y, size, limit) {
numberlist <- build_range(x, y, size)
print_squares(numberlist, limit)
}
# Test build_range
cat("build_range(4, 13, 4):\n")
print(build_range(4, 13, 4))
# Test print_squares
cat("\nprint_squares(3:9, 40):\n")
print_squares(3:9, 40)
# Test print_limit
cat("\nprint_limit(2, 9, 3, 30):\n")
print_limit(2, 9, 3, 30)
# Test with floats
cat("\nprint_limit(2.1, 15.6, 2.5, 35.2):\n")
print_limit(2.1, 15.6, 2.5, 35.2)
# ============================================================
# END OF SCRIPT
# ============================================================
cat("\n========== ALL ACTIVITIES COMPLETED ==========\n")
