# R Foundations: Data Structures, Functions and Control Flow ----
# Video 2 of the R Programming: Zero to Expert series.
# Factors, lists, matrices, data frames, if/else, loops, functions,
# the apply family, strings, dates, CSV files and a mini project.

# Quick recap of video 1 ----
# Vectors, indexing, functions and logical tests.

budget <- c(rent = 900, food = 350, transport = 120, fun = 80)
sum(budget)
budget["food"]
budget[budget > 100]
round(budget / sum(budget) * 100, 1)

class(budget)
length(budget)
is.na(c(4, NA, 7))

# Factors: categories with a fixed set of values ----
# Think t-shirt sizes, blood types, or survey answers.

sizes <- c("medium", "small", "large", "medium",
           "small", "medium", "medium", "large")
sizes
class(sizes)

size_f <- factor(sizes)
size_f
levels(size_f)
nlevels(size_f)

table(size_f)
as.integer(size_f)

size_f <- factor(sizes,
                 levels = c("small", "medium", "large"))
table(size_f)

barplot(table(size_f), col = "steelblue",
        main = "Orders by t-shirt size")

# Ordered factors
# When the categories have a natural ranking, say so.

size_o <- factor(sizes,
                 levels = c("small", "medium", "large"),
                 ordered = TRUE)
size_o
size_o > "small"

size_f > "small"

answers <- c(1, 2, 2, 1, 2, 2, 1)
answers_f <- factor(answers, levels = c(1, 2),
                    labels = c("No", "Yes"))
table(answers_f)

# Pause and try: store these coffee orders as an ordered factor
# "tall", "grande", "venti", "tall", "venti", "grande", "grande"
# Then count them, and test which orders are at least grande.

coffee <- c("tall", "grande", "venti", "tall",
            "venti", "grande", "grande")
coffee_o <- factor(coffee,
                   levels = c("tall", "grande", "venti"),
                   ordered = TRUE)
table(coffee_o)
coffee_o >= "grande"

# Lists: a container that holds anything ----
# Each element can be a different type and a different length.

person <- list(
  name = "Amina",
  age = 29,
  languages = c("Python", "R", "SQL"),
  employed = TRUE
)
person

person$name
person[["languages"]]
person[[2]]
person$languages[2]

# Single vs double square brackets
# [ ] keeps the list wrapper, [[ ]] takes the item out of the box.

person["age"]
class(person["age"])
class(person[["age"]])

person["age"] + 1

person[["age"]] + 1

person$city <- "Nairobi"
person$employed <- NULL
names(person)
length(person)

str(person)

# Nested lists
# A list inside a list, like folders inside folders.

shop <- list(
  name = "Bean There",
  address = list(street = "12 Moi Avenue", city = "Nairobi"),
  menu = c(espresso = 3, latte = 4.5, tea = 2.5)
)
shop$address$city
shop[["menu"]]["latte"]

str(shop)

person$salary

person[[10]]

# Pause and try: make a list describing your favourite movie
# Include a title, a year, a vector of actors and a rating.

movie <- list(
  title = "The Martian",
  year = 2015,
  actors = c("Matt Damon", "Jessica Chastain", "Jeff Daniels"),
  rating = 8
)
movie$actors[2]
paste(movie$title, "came out in", movie$year)

# Matrices: a grid of values with rows and columns ----
# Like a vector, every value must be the same type.

m <- matrix(1:6, nrow = 2)
m
dim(m)

matrix(1:6, nrow = 2, byrow = TRUE)

scores <- matrix(c(78, 85, 92,
                   64, 70, 58,
                   90, 88, 95,
                   55, 81, 73),
                 nrow = 4, byrow = TRUE)
rownames(scores) <- c("Ana", "Ben", "Chen", "Dami")
colnames(scores) <- c("Maths", "English", "Science")
scores

scores[2, 3]
scores["Chen", "English"]
scores[, "Maths"]
scores["Dami", ]

scores[scores < 60]
scores["Ben", "Science"] <- 62
scores["Ben", ]

# apply: run a function over every row or column
# MARGIN = 1 means rows, MARGIN = 2 means columns.

apply(scores, 1, mean)
apply(scores, 2, max)
round(apply(scores, 2, mean), 1)

t(scores)

scores_plus <- cbind(scores, Art = c(80, 75, 85, 90))
scores_plus

# Matrix multiplication (a light touch)

qty <- matrix(c(2, 1, 0,
                1, 2, 3), nrow = 2, byrow = TRUE)
price <- matrix(c(3, 4, 2.5), ncol = 1)
qty %*% price

matrix(c(1, "a", TRUE), nrow = 1)

# Pause and try: find each student's best subject score
# Then count how many scores in the matrix are 80 or above.

apply(scores, 1, max)
sum(scores >= 80)

# Data frames: the spreadsheet of R ----
# Each column is a vector, columns can have different types.

students <- data.frame(
  name  = c("Ana", "Ben", "Chen", "Dami", "Eli", "Fay"),
  age   = c(19, 22, 20, 21, 19, 23),
  city  = c("Nairobi", "Mombasa", "Nairobi", "Kisumu",
            "Mombasa", "Nairobi"),
  score = c(78, 64, 91, 55, 83, 70)
)
students

str(students)
nrow(students)
ncol(students)
names(students)

head(students, 3)
summary(students)

# Selecting columns and rows
# df$column, df[rows, columns], and subset()

students$score
mean(students$score)
max(students$age)

students[2, ]
students[, c("name", "score")]
students[1:3, "city"]

students[students$score > 75, ]

students[students$city == "Nairobi" & students$age < 21, ]

subset(students, score > 75)
subset(students, city == "Nairobi", select = c(name, score))

students[, "height"]

# Adding columns and sorting

students$passed <- students$score >= 60
students$score_pct <- students$score / 100
students

students$score_pct <- NULL
order(students$score)
students[order(students$score), ]

students[order(students$score, decreasing = TRUE), ]
students[order(students$city, -students$score), ]

# Pause and try: which Mombasa students passed?
# Show only their names and ages, oldest first.

mombasa <- subset(students, city == "Mombasa" & passed,
                  select = c(name, age))
mombasa[order(mombasa$age, decreasing = TRUE), ]

# Built-in datasets: mtcars and iris ----
# They are ready to use, no files needed.

head(mtcars)
dim(mtcars)

str(mtcars)

mean(mtcars$mpg)
mtcars[mtcars$mpg > 30, c("mpg", "hp", "wt")]

table(mtcars$cyl)
cyl_f <- factor(mtcars$cyl)
levels(cyl_f)

plot(mtcars$wt, mtcars$mpg,
     xlab = "Weight (1000 lbs)", ylab = "Miles per gallon",
     main = "Heavier cars use more fuel", pch = 19)

# The iris flowers

head(iris, 4)
str(iris)

table(iris$Species)
summary(iris$Petal.Length)

big_petals <- iris[iris$Petal.Length > 6, ]
nrow(big_petals)
table(droplevels(big_petals$Species))

boxplot(Petal.Length ~ Species, data = iris,
        col = c("gold", "tomato", "orchid"),
        main = "Petal length by species")

# Pause and try: mtcars cars with more than 200 horsepower
# Show mpg, cyl and hp, sorted by hp from highest to lowest.

powerful <- mtcars[mtcars$hp > 200, c("mpg", "cyl", "hp")]
powerful[order(powerful$hp, decreasing = TRUE), ]

# Making decisions: if, else if and else ----
# Run some code only when a condition is TRUE.

temperature <- 31
if (temperature > 30) {
  print("It's hot, drink plenty of water!")
}

temperature <- 18
if (temperature > 30) {
  print("It's hot, drink plenty of water!")
} else {
  print("Not too hot today.")
}

temperature <- 12
if (temperature > 30) {
  advice <- "hot"
} else if (temperature > 20) {
  advice <- "warm"
} else if (temperature > 10) {
  advice <- "cool"
} else {
  advice <- "cold"
}
paste("Today feels", advice)

age <- 25
has_ticket <- TRUE
if (age >= 18 && has_ticket) {
  print("Welcome to the concert!")
} else {
  print("Sorry, you can't come in.")
}

temps <- c(31, 18, 12, 25)
if (temps > 30) print("hot")

# ifelse(): the vectorised version
# ifelse(test, value_if_true, value_if_false), for every element.

ifelse(temps > 25, "warm", "cool")
ifelse(temps > 30, "hot",
       ifelse(temps > 15, "mild", "cold"))

students$result <- ifelse(students$score >= 60,
                          "Pass", "Fail")
students[, c("name", "score", "result")]

# switch(): pick one option by name

drink <- "latte"
price <- switch(drink,
  espresso = 3,
  latte = 4.5,
  tea = 2.5,
  0
)
price

day <- "Sat"
switch(day,
  Sat = ,
  Sun = "Weekend, relax!",
  "Weekday, back to work."
)

# Pause and try: classify a number
# Print positive, negative or zero for x <- -7.

x <- -7
if (x > 0) {
  print("positive")
} else if (x < 0) {
  print("negative")
} else {
  print("zero")
}

# Loops: repeating work ----
# for loops walk through a vector, one element at a time.

fruits <- c("mango", "banana", "avocado")
for (fruit in fruits) {
  print(paste("I like", fruit))
}

for (i in 1:5) {
  cat("Round", i, "squared is", i^2, "\n")
}

for (i in seq_along(fruits)) {
  cat(i, ":", fruits[i], "\n")
}

empty <- c()
1:length(empty)
seq_along(empty)

# Building results in a loop
# Create an empty vector of the right length first, then fill it.

prices <- c(120, 45, 80, 300)
with_vat <- numeric(length(prices))
for (i in seq_along(prices)) {
  with_vat[i] <- prices[i] * 1.16
}
with_vat

sales <- c(12, 8, 15, 10, 20)
running <- numeric(length(sales))
total <- 0
for (i in seq_along(sales)) {
  total <- total + sales[i]
  running[i] <- total
}
running

# while loops: repeat until a condition fails
# Use while when you don't know in advance how many steps you need.

savings <- 1000
years <- 0
while (savings < 2000) {
  savings <- savings * 1.08
  years <- years + 1
}
cat("Doubled after", years, "years:", round(savings, 2), "\n")

# repeat, break and next
# break leaves the loop now, next skips to the next pass.

set.seed(42)
rolls <- 0
repeat {
  roll <- sample(1:6, 1)
  rolls <- rolls + 1
  cat("Roll", rolls, "->", roll, "\n")
  if (roll == 6) break
}

for (n in 1:10) {
  if (n %% 2 == 1) next
  cat(n, "is even\n")
}

# Pause and try: FizzBuzz from 1 to 15
# Multiples of 3 print Fizz, of 5 print Buzz, of both FizzBuzz.
# Otherwise print the number itself.

for (n in 1:15) {
  if (n %% 15 == 0) {
    print("FizzBuzz")
  } else if (n %% 3 == 0) {
    print("Fizz")
  } else if (n %% 5 == 0) {
    print("Buzz")
  } else {
    print(n)
  }
}

# Writing your own functions ----
# Package up code you use often, give it a name, reuse it.

greet <- function(name) {
  paste("Hello,", name, "welcome to R!")
}
greet("Wanjiru")
greet("Tom")

to_fahrenheit <- function(celsius) {
  celsius * 9 / 5 + 32
}
to_fahrenheit(25)
to_fahrenheit(c(0, 37, 100))

# Several arguments and default values

add_tax <- function(price, rate = 0.16) {
  price * (1 + rate)
}
add_tax(100)
add_tax(100, rate = 0.2)
add_tax(rate = 0.05, price = 200)

add_tax()

safe_divide <- function(a, b) {
  if (b == 0) {
    return(NA)
  }
  a / b
}
safe_divide(10, 4)
safe_divide(10, 0)

# Returning several values with a list

describe <- function(x) {
  list(
    mean = mean(x),
    range = range(x),
    n_above_mean = sum(x > mean(x))
  )
}
result <- describe(students$score)
result$mean
result$n_above_mean

str(result)

# Scope: what happens inside stays inside
# Variables created inside a function don't exist outside it.

make_discount <- function(price) {
  discount <- 0.1
  price * (1 - discount)
}
make_discount(50)

discount

shop_rate <- 0.05
shop_price <- function(price) price * (1 + shop_rate)
shop_price(100)

# Checking inputs with stop() and stopifnot()
# Fail early with a clear message, instead of a confusing result.

bmi <- function(weight_kg, height_m) {
  stopifnot(is.numeric(weight_kg), is.numeric(height_m))
  if (height_m <= 0) {
    stop("height_m must be positive, in metres")
  }
  round(weight_kg / height_m^2, 1)
}
bmi(70, 1.75)

bmi("70", 1.75)

bmi(70, 0)

# Pause and try: write a tip calculator
# Arguments: bill, tip_pct (default 10) and people (default 1).
# Return a list with the total and the amount per person.

tip_calculator <- function(bill, tip_pct = 10, people = 1) {
  stopifnot(bill > 0, people >= 1)
  total <- bill * (1 + tip_pct / 100)
  list(total = total, per_person = round(total / people, 2))
}
tip_calculator(60)
tip_calculator(85, tip_pct = 15, people = 3)$per_person

# The apply family: loops without writing loops ----
# sapply, lapply, vapply, tapply and mapply.

sapply(1:5, function(x) x^2)
sapply(c(0, 37, 100), to_fahrenheit)

words <- c("data", "science", "is", "fun")
sapply(words, nchar)

sapply(iris[, 1:4], mean)

lapply(1:3, function(x) rep(x, x))

vapply(words, nchar, FUN.VALUE = integer(1))

vapply(words, toupper, FUN.VALUE = numeric(1))

# tapply: summarise by group
# tapply(values, groups, function)

tapply(mtcars$mpg, mtcars$cyl, mean)
round(tapply(iris$Petal.Length, iris$Species, mean), 2)

tapply(students$score, students$city, max)

mapply(function(x, y) x * y, 1:3, 4:6)
mapply(rep, c("a", "b"), c(3, 1))

item <- c("pens", "books", "bags")
qty <- c(10, 2, 1)
unit <- c(0.5, 12, 25)
mapply(function(i, q, u) paste0(i, ": ", q * u),
       item, qty, unit)

# Pause and try: the median of every mtcars column
# Then the average horsepower by number of gears.

sapply(mtcars[, 1:6], median)
tapply(mtcars$hp, mtcars$gear, mean)

# Working with text ----
# Formatting, splitting, searching and replacing.

sprintf("%s scored %d points", "Ana", 78L)
sprintf("Average: %.2f", 73.456)
sprintf("%s: %.1f%%", c("rent", "food"), c(62.07, 24.14))

sprintf("%d items", 3.5)

formatC(1234567.891, format = "f", digits = 2, big.mark = ",")
formatC(c(7, 42, 315), width = 4, flag = "0")
formatC(c("a", "bbb"), width = 5)

city <- "Nairobi"
toupper(city)
tolower(city)

# Splitting text with strsplit()

record <- "Ana,19,Nairobi,78"
parts <- strsplit(record, ",")
parts
parts[[1]][3]

full_names <- c("Grace Achieng", "Peter Mwangi", "Lucy Wambui")
first <- sapply(strsplit(full_names, " "), function(p) p[1])
first

# Searching and replacing: grepl, sub and gsub

products <- c("green tea", "black coffee", "iced tea",
              "espresso", "TEA latte")
grepl("tea", products)
products[grepl("tea", products, ignore.case = TRUE)]

phone <- "0712-345-678"
sub("-", " ", phone)
gsub("-", "", phone)

prices_txt <- c("KSh 1,200", "KSh 450", "KSh 12,500")
clean <- gsub("KSh |,", "", prices_txt)
clean
sum(as.numeric(clean))

# Pause and try: tidy up these email addresses
# emails <- c(" Ana@Gmail.com", "ben@yahoo.com ", "CHEN@gmail.COM")
# Remove the spaces, make them lowercase, then find the gmail ones.

emails <- c(" Ana@Gmail.com", "ben@yahoo.com ", "CHEN@gmail.COM")
emails <- tolower(gsub(" ", "", emails))
emails
emails[grepl("gmail", emails)]

# Dates ----

today <- Sys.Date()
today
class(today)

launch <- as.Date("2026-03-15")
launch + 30
as.Date("2026-12-25") - launch
weekdays(launch)

as.Date("15/03/2026", format = "%d/%m/%Y")
format(launch, "%d %B %Y")
format(launch, "%A")

birthday <- as.Date("1998-07-04")
days_alive <- as.numeric(launch - birthday)
days_alive
floor(days_alive / 365.25)

paydays <- seq(as.Date("2026-01-31"), by = "month",
                length.out = 4)
paydays
format(paydays, "%b")

# Reading and writing CSV files ----
# write.csv() saves a data frame, read.csv() loads one.

write.csv(students, "students.csv", row.names = FALSE)
file.exists("students.csv")

students_back <- read.csv("students.csv")
str(students_back)

write.csv(students, "oops.csv")
head(read.csv("oops.csv"), 3)

nairobi <- read.csv("students.csv")
nairobi <- nairobi[nairobi$city == "Nairobi", ]
write.csv(nairobi, "nairobi_students.csv", row.names = FALSE)
nrow(read.csv("nairobi_students.csv"))

# Mini project: a student grades report ----
# Data frame -> averages -> grade letters -> summaries -> CSV.

grades <- data.frame(
  student = c("Amani", "Brian", "Cynthia", "David", "Esther",
              "Felix", "Grace", "Hassan", "Imani", "Joseph"),
  maths   = c(85, 62, 91, 45, 74, 58, 79, 67, 88, 53),
  english = c(78, 70, 88, 52, 81, 64, 85, 72, 90, 49),
  science = c(92, 58, 95, 48, 69, 61, 82, 70, 84, 57)
)
str(grades)

grades$average <- round(apply(grades[, 2:4], 1, mean), 1)
head(grades)

letter_grade <- function(score) {
  stopifnot(is.numeric(score), length(score) == 1)
  if (score >= 80) {
    "A"
  } else if (score >= 70) {
    "B"
  } else if (score >= 60) {
    "C"
  } else if (score >= 50) {
    "D"
  } else {
    "F"
  }
}
letter_grade(74.7)

letter_grade(grades$average)

letters_loop <- character(nrow(grades))
for (i in seq_along(grades$average)) {
  letters_loop[i] <- letter_grade(grades$average[i])
}
letters_loop

grades$grade <- sapply(grades$average, letter_grade)
identical(grades$grade, letters_loop)

grades$grade <- factor(grades$grade,
                       levels = c("A", "B", "C", "D", "F"))
table(grades$grade)
round(tapply(grades$average, grades$grade, mean), 1)

barplot(table(grades$grade),
        col = c("darkgreen", "seagreen", "gold", "orange", "red"),
        main = "Grade distribution", ylab = "Students")

grades$status <- ifelse(grades$average >= 60,
                        "On track", "Needs support")
grades[grades$status == "Needs support", c("student", "average")]

ranked <- grades[order(grades$average, decreasing = TRUE), ]
for (i in 1:3) {
  cat(sprintf("%d. %-8s %5.1f  (%s)\n", i, ranked$student[i],
              ranked$average[i], ranked$grade[i]))
}

report <- grades[, c("student", "average", "grade", "status")]
report <- report[order(report$student), ]
write.csv(report, "grades_report.csv", row.names = FALSE)
head(read.csv("grades_report.csv"), 4)

# Recap ----
# Factors, lists, matrices and data frames to store data.
# if/else, ifelse, switch, for, while, repeat, break, next.
# Functions with defaults and checks, the apply family,
# text, dates, and reading and writing CSV files.