TExcelTAD
Home › R › R Exercises

R Exercises

Time to practise! Each exercise has a starter playground that already runs and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run and compare your output with the "Expected" lines. If you get stuck, open the solution, but give it a few minutes first.

# Exercise Topics
1 Temperature table vectors, sprintf()
2 FizzBuzz loops, if, %%
3 Vowel counter strings, regular expressions
4 Grade report data frames, cut(), factors
5 Robust summary functions, lists, missing values
6 Digit sum recursion
7 Times table matrices, outer()
8 Group means tapply(), aggregate()
9 Stopping distance lm(), predict()

1. Temperature table

Print a conversion table from Celsius to Fahrenheit for 0, 10, 20, 30 and 40 °C using F = C × 9/5 + 32. Each row should look like 0 C = 32.0 F (Celsius right-aligned in 3 characters, Fahrenheit in 5 with one decimal). Try to do it without a loop: sprintf() is vectorised.

Expected first line: 0 C = 32.0 F, last line: 40 C = 104.0 F.

r · try it yourself
celsius <- 0        # TODO: all five values
fahrenheit <- 0     # TODO: use the formula
cat(celsius, "C =", fahrenheit, "F\n")
0 C = 0 F
Show solution
r
celsius <- seq(0, 40, by = 10)
fahrenheit <- celsius * 9 / 5 + 32
cat(sprintf("%3d C = %5.1f F\n", as.integer(celsius), fahrenheit), sep = "")

%d needs integers, hence as.integer(). sep = "" stops cat() from adding a space before each line.

2. FizzBuzz

For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise, all on one line.

Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

r · try it yourself
out <- character(15)
for (i in 1:15) {
  out[i] <- as.character(i)   # TODO: Fizz / Buzz / FizzBuzz
}
cat(out, "\n")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
r
out <- character(15)
for (i in 1:15) {
  out[i] <- if (i %% 15 == 0) "FizzBuzz"
            else if (i %% 3 == 0) "Fizz"
            else if (i %% 5 == 0) "Buzz"
            else as.character(i)
}
cat(out, "\n")

# Vectorised alternative:
n <- 1:15
cat(ifelse(n %% 15 == 0, "FizzBuzz",
      ifelse(n %% 3 == 0, "Fizz",
        ifelse(n %% 5 == 0, "Buzz", n))), "\n")

Check 15 first: a multiple of 15 is also a multiple of 3 and 5.

3. Vowel counter

Write count_vowels(text) that returns how many vowels (a e i o u, any case) each string contains. It should work on a whole character vector.

Expected: count_vowels("Statistical Computing") is 7, and count_vowels(c("R", "AEIOU xyz", "banana")) is 0 5 3.

r · try it yourself
count_vowels <- function(text) {
  0   # TODO
}
count_vowels("Statistical Computing")
count_vowels(c("R", "AEIOU xyz", "banana"))
[1] 0
[1] 0
Show solution
r
count_vowels <- function(text) {
  nchar(gsub("[^aeiou]", "", tolower(text)))
}

Remove everything that is not a vowel, then count what is left. Both gsub() and nchar() are vectorised, so the function handles vectors for free.

4. Grade report

Given the scores below, add a grade column: A for 80–100, B for 65–79, C for 50–64 and F below 50. Then print how many students got each grade and the name of the top student.

Expected counts: F 1, C 1, B 2, A 2; top student: "Ana".

r · try it yourself
students <- data.frame(
  name = c("Ana", "Ben", "Cai", "Dee", "Eli", "Fay"),
  score = c(91, 58, 74, 66, 85, 47)
)
students$grade <- "?"   # TODO: use cut()
students
  name score grade
1  Ana    91     ?
2  Ben    58     ?
3  Cai    74     ?
4  Dee    66     ?
5  Eli    85     ?
6  Fay    47     ?
Show solution
r
students$grade <- cut(students$score, breaks = c(0, 49, 64, 79, 100),
                      labels = c("F", "C", "B", "A"))
students
table(students$grade)
students$name[students$score == max(students$score)]

cut() uses intervals that are closed on the right, so (49, 64] covers 50 to 64 for whole-number scores.

5. Robust summary

Write describe(x) that ignores missing values and returns a list with n (number of non-missing values), mean and sd, both rounded to 2 decimals.

Expected for c(4, 8, NA, 15, 16, 23, 42): n = 6, mean = 18, sd = 13.49.

r · try it yourself
describe <- function(x) {
  list(n = length(x), mean = mean(x), sd = sd(x))   # TODO: handle NA, round
}
str(describe(c(4, 8, NA, 15, 16, 23, 42)))
List of 3
 $ n   : int 7
 $ mean: num NA
 $ sd  : num NA
Show solution
r
describe <- function(x) {
  x <- x[!is.na(x)]
  list(n = length(x), mean = round(mean(x), 2), sd = round(sd(x), 2))
}
describe(c(4, 8, NA, 15, 16, 23, 42))$sd   # 13.49

Removing the NAs once at the start is simpler than passing na.rm = TRUE to every function, and it makes length() count only real values.

6. Digit sum

Write a recursive function digit_sum(n) that adds up the digits of a non-negative whole number. Hint: n %% 10 is the last digit and n %/% 10 drops it.

Expected: digit_sum(2024) is 8; sapply(c(7, 99, 12345), digit_sum) is 7 18 15.

r · try it yourself
digit_sum <- function(n) {
  n   # TODO: base case + recursive case
}
digit_sum(2024)
sapply(c(7, 99, 12345), digit_sum)
[1] 2024
[1]     7    99 12345
Show solution
r
digit_sum <- function(n) {
  if (n < 10) return(n)                 # base case: a single digit
  (n %% 10) + digit_sum(n %/% 10)       # last digit + sum of the rest
}

7. Times table

Build a 5 × 5 multiplication table as a matrix with rows and columns labelled 1 to 5, print it, and print the sum of its diagonal (the squares 1, 4, 9, 16, 25).

Expected: the bottom-right value is 25 and the diagonal sum is 55.

r · try it yourself
m <- matrix(0, nrow = 5, ncol = 5)   # TODO: fill with products
m
sum(diag(m))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0
[1] 0
Show solution
r
m <- outer(1:5, 1:5)          # every product of the two vectors
dimnames(m) <- list(1:5, 1:5)
m
sum(diag(m))

outer(x, y) applies * to every pair of elements, which is exactly a times table. A nested for loop filling m[i, j] <- i * j works too.

8. Group means

Using mtcars, compute the average miles per gallon (mpg) for each number of gears (gear), rounded to 2 decimals.

Expected: 3: 16.11, 4: 24.53, 5: 21.38.

r · try it yourself
mean(mtcars$mpg)   # TODO: one mean per gear group
[1] 20.09062
Show solution
r
round(tapply(mtcars$mpg, mtcars$gear, mean), 2)
# or, as a data frame:
aggregate(mpg ~ gear, data = mtcars, FUN = function(v) round(mean(v), 2))

9. Stopping distance

The cars data set records the speed (mph) and stopping distance (ft) of 50 cars. Fit a linear model of dist on speed, predict the stopping distance at 21 mph (rounded to 1 decimal) and print the model's R² (3 decimals).

Expected: a prediction of 65 ft and an R² of 0.651.

r · try it yourself
fit <- NULL   # TODO: lm(...)
cat("Not fitted yet\n")
Not fitted yet
Show solution
r
fit <- lm(dist ~ speed, data = cars)
round(predict(fit, data.frame(speed = 21)), 1)
round(summary(fit)$r.squared, 3)

predict() needs a data frame whose column is named like the predictor (speed).

Test yourself

Which function turns numeric scores into labelled grade bands?

  1. table()
  2. cut()
  3. split()
  4. factor(levels = )

What does outer(1:3, 1:3) return?

  1. The vector 1 4 9
  2. A 3 × 3 matrix of products
  3. The number 14
  4. A list