Mathew K Analytics

Lesson 2 · R Programming: Zero to Expert

R Programming: Data Structures, Functions & Loops (Full Course) | R 102

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…

⬇ Download R script⬇ R notebook (.ipynb)

What you'll learn

Files for this lesson

Save these in one folder, open the script in RStudio and set that folder as the working directory (Session → Set Working Directory → To Source File Location).

📓 Full notebook

Download .ipynb

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.

R script: 02_r_foundations.R. Download it from this page and open it in RStudio, or run this notebook with an R kernel (for example in Google Colab: Runtime → Change runtime type → R).

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)

The total is 1450. Food on its own is 350. Three categories are above one hundred: rent, food and transport. Fun, at 80, is dropped. And rent takes 62.1 percent of the budget, food 24.1, transport 8.3 and fun 5.5.

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

Numeric, four elements, and is dot n a gives FALSE, TRUE, FALSE, because only the middle value is missing.

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)

We see the eight sizes in quotes, and the class is character. R has no idea these are categories.

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

Now the values print without quotes, and underneath R shows a Levels line: large, medium, small. There are three levels, and notice they are in alphabetical order. We'll fix that in a moment.

table(size_f)
as.integer(size_f)

table counts two large, four medium and two small. The integer codes show that large is 1, medium is 2 and small is 3, simply because that's the alphabetical order of the levels.

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

Same counts, but now in a sensible order: two small, four medium, two large. Tables and plots will follow this order from now on.

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

In the Plots pane we get three bars in the order small, medium, large, and medium clearly towers over the other two.

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"

The levels line now reads small, less than medium, less than large, showing the ranking. The comparison returns TRUE for every medium and large order, and FALSE for the two small ones.

size_f > "small"

R gives a warning that this is not meaningful for factors, and returns NA for every element. Unordered factors simply can't be ranked.

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

The numbers have become No and Yes, and the table shows three No answers and four Yes answers.

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"

We get two tall, three grande and two venti. And the comparison is TRUE for five of the seven orders: all the grandes and ventis.

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

Each element is printed under its own name, with a dollar sign label in front: the name Amina, age 29, three languages, and employed TRUE. Four completely different kinds of data living happily in one object.

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

We get Amina, then the vector Python, R and SQL, then 29, and finally just R, the second language.

Single vs double square brackets#

[ ] keeps the list wrapper, [[ ]] takes the item out of the box.

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

Single brackets print with the dollar sign label, because the result is still a list of one element. The classes confirm it: list for single brackets, numeric for double brackets. Only the double bracket version can be used in arithmetic.

person["age"] + 1

An error: non numeric argument to binary operator. You can't add one to a list.

This one is meant to fail, so you can see the error message.

person[["age"]] + 1

Now we get 30, exactly as expected.

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

The names are now name, age, languages and city. Employed is gone, city was added, so the length is still four.

str(person)

str shows it's a list of four, then one line per element with its type and first values: character, number, a character vector of three, and character.

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"]

We get Nairobi, and the latte costs 4.5. You simply drill down one level at a time.

str(shop)

str shows the nesting with indentation. The address appears as a list of two inside the main list, and the menu is a named numeric vector.

person$salary

It quietly returns NULL. That can hide typos, so always check your spelling.

person[[10]]

Subscript out of bounds. Our list only has four elements, so there is no tenth one.

This one is meant to fail, so you can see the error message.

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)

The second actor is Jessica Chastain, and paste gives us The Martian came out in 2015.

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)

We get two rows and three columns. Notice that R fills the matrix column by column: 1 and 2 go down the first column, 3 and 4 down the second. dim confirms it: 2 rows, 3 columns.

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

Now the first row reads 1, 2, 3 and the second row 4, 5, 6.

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

A tidy grid: Ana, Ben, Chen and Dami down the side, Maths, English and Science across the top. Chen has the highest scores, ninety, eighty eight and ninety five.

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

Ben scored 58 in science and Chen 88 in English. The maths column gives 78, 64, 90 and 55, and Dami's row is 55, 81 and 73. The empty slot before or after the comma means everything.

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

Two scores were below sixty, 55 and 58. After the retake, Ben's row reads 64, 70 and 62.

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)

Chen has the best average at 91, and Ben the lowest at 65.33. The top scores are 90 in maths, 88 in English and 95 in science, and the subject averages, rounded, are 71.8 for maths, 81 for English and 80.5 for science.

t(scores)

Now the subjects run down the side and the students across the top. Same numbers, rotated.

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

A fourth column called Art now appears on the right, with 80, 75, 85 and 90. Its sibling, r bind, adds rows in the same way.

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

Customer one spends 10 and customer two spends 18.5. Two times three plus one times four is ten, and three plus eight plus seven fifty is eighteen fifty.

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

Everything has been turned into text, with quotes around 1, a and TRUE. A matrix can only hold one type, so R converts everything to the most flexible one, character.

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)

The best scores are 92 for Ana, 70 for Ben, 95 for Chen and 81 for Dami. Six of the twelve scores are eighty or above.

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

Six rows and four columns, with the row numbers one to six on the left. Text and numbers sit side by side, which a matrix could never do.

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

str says this is a data frame with 6 observations of 4 variables, then shows each column's type: name and city are character, age and score are numeric. Then 6 rows, 4 columns, and the column names name, age, city and score.

head(students, 3)
summary(students)

head prints just Ana, Ben and Chen. summary gives the minimum, quartiles, median, mean and maximum for the numeric columns. The average score is 73.5, ranging from 55 to 91. The text columns just show their length and class.

Selecting columns and rows#

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

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

We get the six scores, a mean of 73.5, and the oldest student is 23.

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

Row two is Ben from Mombasa. Then a two column table of names and scores. And the first three cities: Nairobi, Mombasa, Nairobi.

students[students$score > 75, ]

Three students: Ana with 78, Chen with 91 and Eli with 83. Notice their original row numbers, 1, 3 and 5, are kept.

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

Only Ana and Chen match. Fay also lives in Nairobi, but she is 23.

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

The first gives the same three high scorers. The second shows only the names and scores of the three Nairobi students: Ana, Chen and Fay.

students[, "height"]

Undefined columns selected. There is no height column, so R refuses.

This one is meant to fail, so you can see the error message.

Adding columns and sorting#

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

Two new columns appear on the right. Everyone passed except Dami, with 55, and the proportions run from 0.55 to 0.91.

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

order gives 4, 2, 6, 1, 5, 3, meaning row 4, Dami, has the lowest score. Using it as the row index lists the students from lowest score, Dami with 55, up to Chen with 91.

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

First Chen, Eli and Ana lead the leaderboard. In the second table Kisumu comes first, then Mombasa with Eli before Ben, then Nairobi with Chen, Ana and Fay in descending 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), ]

Both Mombasa students passed, so we see Ben, aged 22, first and then Eli, aged 19.

Built-in datasets: mtcars and iris#

They are ready to use, no files needed.

head(mtcars)
dim(mtcars)

Each row is a car model, like the Mazda RX4 and the Datsun 710, and the columns include mpg for miles per gallon, cyl for cylinders and hp for horsepower. dim tells us there are 32 cars and 11 columns. Here the car names are row names, not a column.

str(mtcars)

All eleven columns are numeric. Even am, the transmission, is stored as 0 for automatic and 1 for manual.

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

The average is about 20.09 miles per gallon. Four cars beat thirty: the Fiat 128, the Honda Civic, the Toyota Corolla and the Lotus Europa. They are all small, light cars, each weighing well under two and a half thousand pounds.

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

There are 11 four cylinder cars, 7 six cylinder cars and 14 eight cylinder cars, and the factor's levels are 4, 6 and 8.

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

The scatter plot slopes clearly downwards. The light cars on the left do over thirty miles per gallon, while the heaviest cars, above five thousand pounds, manage only around ten to fifteen.

The iris flowers#

head(iris, 4)
str(iris)

Four measurements of the petals and sepals in centimetres, plus the species. str reveals that Species is a factor with three levels: setosa, versicolor and virginica. So factors appear in real data all the time.

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

There are exactly 50 flowers of each species. Petal length ranges from 1 to 6.9 centimetres, with a median of 4.35 and a mean of about 3.76.

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

Nine flowers have petals over six centimetres, and every single one is virginica. Without drop levels, the table would also show setosa and versicolor with zero.

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

Three boxes side by side. Setosa's petals are tiny, all under two centimetres, versicolor sits in the middle around four, and virginica has the longest petals, around five and a half.

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), ]

Seven cars qualify. The Maserati Bora leads with 335 horsepower, and every one of them has eight cylinders and poor fuel economy, between 10.4 and 15.8 miles per gallon.

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!")
}

The condition is TRUE, so R prints: 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.")
}

Eighteen is not above thirty, so the else branch runs and we see: 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)

Twelve fails the first two tests but passes the third, so advice becomes cool and we see: Today feels cool. As soon as one branch matches, R skips all the others.

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

Both are TRUE, so we see Welcome to the concert! The double vertical bar works the same way for or.

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

An error: the condition has length greater than one. if needs exactly one TRUE or FALSE, not four.

This one is meant to fail, so you can see the error message.

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"))

The first gives warm, cool, cool, cool. Twenty five is not above twenty five, so it counts as cool. The nested version gives hot, mild, cold, mild.

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

A new result column says Pass for everyone except Dami, who scored 55 and gets Fail.

switch(): pick one option by name#

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

Latte matches, so the price is 4.5.

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

Saturday has no value of its own, so it uses Sunday's: Weekend, relax!

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")
}

Minus seven fails the first test and passes the second, so we see negative.

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))
}

Three lines: I like mango, I like banana, I like avocado. The body ran three times, once per fruit.

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

Five lines, from Round 1 squared is 1, up to Round 5 squared is 25.

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

We see 1 mango, 2 banana and 3 avocado, each position next to its value.

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

One to length of an empty vector gives 1 and 0, so a loop would run twice with nonsense values. seq along correctly gives integer of length zero, so a loop wouldn't run at all. That's why seq along is the safer habit.

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

The prices with tax are 139.2, 52.2, 92.8 and 348.

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

The running total climbs 12, 20, 35, 45 and finally 65. Each value depends on the one before, which is perfect for a loop.

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")

It takes 10 years to double, ending with 2158.92. The loop checked the condition before every pass and stopped as soon as it was FALSE.

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
}

With seed forty two, the rolls are 1, 5, 1, 1, 2, 4, 2, 2, 1, 4, 1, 5, and finally a 6 on roll 13. Then break stops the loop.

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

We see 2, 4, 6, 8 and 10 is even. The odd numbers were skipped by next.

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)
  }
}

We get 1, 2, Fizz, 4, Buzz, Fizz, and so on, and the final line is FizzBuzz for fifteen. If you checked three first, fifteen would wrongly print Fizz. Order of conditions really matters.

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")

Hello, Wanjiru welcome to R! and then Hello, Tom welcome to R! The function returns the last value it calculates, and greet now also appears in the Environment pane, under Functions.

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

Twenty five Celsius is 77 Fahrenheit. And the vector gives 32 for freezing, 98.6 for body temperature and 212 for boiling water.

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)

We get 116 with the default rate, 120 with twenty percent, and 210 with five percent tax on two hundred.

add_tax()

Error: argument price is missing, with no default. Price has no default value, so R can't continue.

This one is meant to fail, so you can see the error message.

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

Ten divided by four is 2.5, and dividing by zero gives NA instead of infinity.

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

The mean is 73.5, and three students scored above it.

str(result)

A list of three: the mean, a range of 55 to 91, and the count of 3.

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)

Fifty with ten percent off is 45.

discount

Error: object discount not found. It only existed while the function was running, so it never appears in your Environment pane.

This one is meant to fail, so you can see the error message.

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

We get 105, because the function found shop rate in the global environment.

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)

Seventy kilograms at one point seven five metres gives a B M I of 22.9.

bmi("70", 1.75)

stop if not catches it, saying is numeric weight kg is not TRUE.

This one is meant to fail, so you can see the error message.

bmi(70, 0)

Our own message appears: height m must be positive, in metres. Much clearer than a division by zero.

This one is meant to fail, so you can see the error message.

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

Sixty with the default tip gives a total of 66, and per person also 66 because it's one person. For the dinner, each of the three people pays 32.58.

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)

The first gives 1, 4, 9, 16 and 25. The second converts all three temperatures with our own function: 32, 98.6 and 212. The s in s apply stands for simplify. It tidies the results into a simple vector.

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

We get a named vector: data has 4 letters, science 7, is 2 and fun 3. s apply even uses the words as names.

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

Sepal length averages 5.84, sepal width 3.06, petal length 3.76 and petal width about 1.2 centimetres. One line replaced four separate calls.

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

The result is a list of three: the first holds one 1, the second two 2s, and the third three 3s. They have different lengths, so a list is the natural container.

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

The same counts as before, 4, 7, 2 and 3. v apply checked that every result really was a single integer.

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

An error saying values must be type double, but the result is type character. v apply refuses rather than silently giving you the wrong type, which is why it's great inside your own functions.

This one is meant to fail, so you can see the error message.

tapply: summarise by group#

tapply(values, groups, function)

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

Four cylinder cars average 26.66 miles per gallon, six cylinders 19.74, and eight cylinders just 15.1. For iris, setosa petals average 1.46 centimetres, versicolor 4.26 and virginica 5.55.

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

Kisumu's best is 55, Mombasa's is 83 and Nairobi's is 91.

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

The first gives 4, 10 and 18: one times four, two times five and three times six. The second returns a list named a and b, holding three a's and one b.

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)

We get pens: 5, books: 24 and bags: 25, each one named after its item.

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)

The median car does 19.2 miles per gallon with 6 cylinders and 123 horsepower. Three gear cars average about 176 horsepower, four gear cars 89.5, and five gear cars about 196.

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))

We get Ana scored 78 points, then Average: 73.46, rounded to two decimals. The last call produces two strings at once: rent: 62.1 percent and food: 24.1 percent.

sprintf("%d items", 3.5)

An error: invalid format, use format f, e, g or a for numeric objects. For decimals, use percent f instead.

This one is meant to fail, so you can see the error message.

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

The big number becomes 1,234,567.89. The IDs become 0007, 0042 and 0315. And the text is padded with spaces on the left, so both strings are five characters wide.

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

NAIROBI in capitals and nairobi in lowercase. tolower is very handy for comparing text typed by different people.

Splitting text with strsplit()#

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

strsplit returns a list containing one vector of four pieces: Ana, 19, Nairobi and 78, all as text. And the third piece is Nairobi.

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

We get just the first names: Grace, Peter and Lucy.

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)]

grepl gives TRUE, FALSE, TRUE, FALSE, FALSE. It missed the capital TEA, because matching is case sensitive. With ignore case, all three tea products are found: green tea, iced tea and TEA latte.

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

sub changed just the first dash into a space, while gsub removed both dashes to give 0712345678.

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

The cleaned text is 1200, 450 and 12500, and their sum is 14150. Without cleaning, as numeric would have given NA.

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)]

The clean emails are ana at gmail dot com, ben at yahoo dot com and chen at gmail dot com. Two of them, Ana's and Chen's, are gmail addresses.

Dates#

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

You'll see today's date written as year, month, day, and the class is Date. Your date will of course be different from mine.

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

Thirty days after the fifteenth of March is the fourteenth of April. Christmas is 285 days after the launch, which R reports as a time difference, and the launch day itself is a Sunday.

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

The text is converted into the proper date 2026-03-15. format then writes it as 15 March 2026, and the weekday as Sunday.

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

On launch day this person had been alive for 10116 days, which makes them 27 years old.

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

Hmm, look closely. We get the 31st of January, then the 3rd of March, the 31st of March and the 1st of May. February has no 31st, so R rolled over into March. Dates have tricky corners, and in video three a package called lubridate will make this much easier. The short month names come out as Jan, Mar, Mar and May.

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")

TRUE, the file is there. You'll also see it appear in the Files pane.

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

Six observations of six variables, exactly what we saved. The passed column came back as logical, the scores as integers, and the text as character.

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

An extra column called X has appeared at the front, holding the old row numbers 1, 2 and 3. This catches out almost everyone at least once.

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"))

The new file holds 3 rows: Ana, Chen and Fay. A complete read, filter, write round trip.

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)

A data frame with 10 observations of 4 variables: the student names as character, and three numeric score columns.

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

A new average column appears. Amani averages 85, Brian 63.3, Cynthia an impressive 91.3, and David just 48.3.

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)

Seventy four point seven is a B, exactly as expected.

letter_grade(grades$average)

stop if not catches it: length of score equals one is not TRUE. Our input check did its job.

This one is meant to fail, so you can see the error message.

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

We get A, C, A, F, B, C, A, C, A and D.

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

TRUE. The loop and s apply agree perfectly. Most R programmers would choose the s apply version because it's shorter and clearer.

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

Four A grades, one B, three Cs, one D and one F. The A students average 86.4, the B student 74.7, the C students 64.7, and the D and F students 53 and 48.3.

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

Five bars in grade order. The A bar is tallest at four students, C comes second with three, and B, D and F each have one.

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

Two students: David with 48.3 and Joseph with 53. The teacher now knows exactly who to help.

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]))
}

The podium: first Cynthia with 91.3, second Imani with 87.3, and third Amani with 85, all with an A.

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)

The saved report reads back perfectly: Amani 85 A on track, Brian 63.3 C on track, Cynthia 91.3 A, and David 48.3 F needing support.

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.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.