Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

R Practice Exercises with Solutions: Strings to Regression

Fifteen graded R exercises with full solutions: strings, regular expressions, dates, statistics, distributions, tests, regression, functional programming, S3, error handling and ggplot2.

You learn R by writing R. This lesson gives you fifteen exercises that revisit the second half of the course: text and dates, statistics and models, functions and objects, and a plot. Try each one before reading the solution; even a failed attempt teaches you more than reading. Every exercise has a short task, a hint and a worked solution. Solutions show the output only where it is certain, and the Python block at the end lets you check the numeric answers.

R is not available on this site, so run the code in R or RStudio. For each exercise, write your own answer first, then compare. There are usually several correct solutions; yours does not have to match.

Part 1: Strings, regular expressions and dates

Exercise 1: Clean up names

Turn c(" alice SMITH ", "BOB jones", "carol Lee") into properly capitalized names with single spaces: "Alice Smith", "Bob Jones", "Carol Lee".

Hint: trim, collapse spaces, lowercase, then capitalize the first letter of every word.

R
clean_name <- function(x) {
  x <- tolower(gsub("\\s+", " ", trimws(x)))
  words <- strsplit(x, " ")
  vapply(words,
         \(w) paste0(toupper(substring(w, 1, 1)), substring(w, 2), collapse = " "),
         character(1))
}
clean_name(c("  alice SMITH ", "BOB jones", "carol   Lee"))
# "Alice Smith" "Bob Jones"   "Carol Lee"

Each name is split into words; paste0() capitalizes every word at once (it is vectorized), and collapse = " " glues the words back together. vapply() guarantees one string per name.

Exercise 2: Extract hashtags

From post <- "Loving #rstats and #DataScience today! #fun" extract every hashtag.

R
regmatches(post, gregexpr("#\\w+", post))[[1]]
# "#rstats" "#DataScience" "#fun"

#\\w+ means a hash followed by one or more word characters. gregexpr() finds all matches, regmatches() pulls them out, and [[1]] unwraps the list for the single input string. With stringr: str_extract_all(post, "#\\w+")[[1]].

Exercise 3: Counting days

How many days are there from 15 March 2026 to the end of that year, and which weekday is 31 December 2026?

R
d1 <- as.Date("2026-03-15")
d2 <- as.Date("2026-12-31")
as.numeric(d2 - d1)       # 291
weekdays(d2)              # "Thursday"

The subtraction gives a difftime; as.numeric() strips the unit. Cross-check: 285 days to 25 December plus 6 more. (Jan 1, 2026 was a Thursday and 2026 has 365 days, so 31 December is also a Thursday.)

Exercise 4: Quarter starts

Create the first day of each quarter of 2026.

R
seq(as.Date("2026-01-01"), by = "quarter", length.out = 4)
# "2026-01-01" "2026-04-01" "2026-07-01" "2026-10-01"

Part 2: Statistics

Exercise 5: Summarize and find the outlier

For x <- c(12, 15, 11, 18, 25, 14, 13) compute the mean, median, sample standard deviation, and decide with the 1.5 x IQR rule whether any value is an outlier.

R
x <- c(12, 15, 11, 18, 25, 14, 13)
mean(x)      # 15.42857
median(x)    # 14
sd(x)        # 4.790864
q <- quantile(x, c(0.25, 0.75))   # 12.5 and 16.5
iqr <- IQR(x)                     # 4
x[x < q[1] - 1.5 * iqr | x > q[2] + 1.5 * iqr]    # 25

The fences are 12.5 - 6 = 6.5 and 16.5 + 6 = 22.5, so 25 is an outlier. Notice how it pulls the mean (15.4) above the median (14). See descriptive statistics.

Exercise 6: Probabilities

(a) A basketball player makes 40 percent of her shots. In 5 independent shots, what is the probability of making at least 3? (b) IQ scores follow a normal distribution with mean 100 and sd 15. What fraction of people score above 130, and what score marks the top 1 percent?

R
1 - pbinom(2, size = 5, prob = 0.4)           # 0.31744   (a)
pnorm(130, mean = 100, sd = 15, lower.tail = FALSE)    # 0.02275013   (b) about 2.3%
qnorm(0.99, mean = 100, sd = 15)              # 134.8952   score of the top 1%

"At least 3" is "more than 2", so subtract P(X <= 2) from 1 (or use lower.tail = FALSE). For (b), 130 is two standard deviations above the mean. See probability distributions.

Exercise 7: Is this die fair?

A die is rolled 60 times with face counts 8, 12, 9, 11, 10, 10. Test whether it is fair.

R
counts <- c(8, 12, 9, 11, 10, 10)
chisq.test(counts)
# X-squared = 1, df = 5, p-value = 0.9626

By default chisq.test() compares the counts with equal expected probabilities (10 each). The statistic is (4 + 4 + 1 + 1 + 0 + 0) / 10 = 1. The p-value of 0.96 is very large: the counts are entirely consistent with a fair die. See hypothesis tests.

Exercise 8: Stopping distance

R's built-in cars data frame has the speed (mph) and stopping distance (feet) of 50 cars. Fit a linear model of dist on speed, read off the slope and R-squared, and predict the distance at 20 mph.

R
fit <- lm(dist ~ speed, data = cars)
coef(fit)                       # (Intercept) -17.579095   speed 3.932409
summary(fit)$r.squared          # 0.6510794
predict(fit, data.frame(speed = 20))    # 61.06908

Each extra mph is associated with about 3.93 extra feet of stopping distance, and speed explains about 65 percent of the variation. The negative intercept (a car at 0 mph needs -17.6 feet) shows why intercepts should not be interpreted outside the data range (speeds 4 to 25). See regression.

Part 3: Functions, objects and errors

Exercise 9: Functional pipeline

Without a loop, (a) compute 5! (b) get the length of every word in "the quick brown fox".

R
Reduce(`*`, 1:5)                                   # 120
words <- strsplit("the quick brown fox", " ")[[1]]
sapply(words, nchar)
#   the quick brown   fox 
#     3     5     5     3 

sapply() names the result with the words because the input is a character vector. See functional programming.

Exercise 10: An S3 shape

Create rect(w, h) and circle(r) objects and a generic area() so that area(rect(3, 4)) is 12 and area(circle(1)) is pi.

R
rect   <- function(w, h) structure(list(w = w, h = h), class = "rect")
circle <- function(r)    structure(list(r = r),        class = "circle")

area <- function(shape, ...) UseMethod("area")
area.rect   <- function(shape, ...) shape$w * shape$h
area.circle <- function(shape, ...) pi * shape$r^2
area.default <- function(shape, ...) stop("don't know how to compute the area of this", call. = FALSE)

area(rect(3, 4))     # 12
area(circle(1))      # 3.141593

Adding a new shape (a triangle) means adding one more method; the generic never changes. See OOP in R.

Exercise 11: A forgiving logarithm

Write safe_log(x) that returns NA instead of failing or warning when the input is text or negative.

R
safe_log <- function(x) {
  tryCatch(log(x),
           error   = function(e) NA_real_,
           warning = function(w) NA_real_)
}
safe_log(100)    # 4.60517
safe_log(-1)     # NA   (log(-1) would give NaN with a warning)
safe_log("a")    # NA   (log("a") is an error)

tryCatch() catches both condition types. In real code, catching every error and returning NA can hide bugs; decide on purpose which conditions you expect. See error handling.

Exercise 12: Vectorize it

Rewrite without a loop: the sum of the squares of the odd numbers from 1 to 99.

R
total <- 0
for (i in 1:99) if (i %% 2 == 1) total <- total + i^2
total                        # 166650

sum(seq(1, 99, by = 2)^2)    # 166650

Check with the formula for the first n odd squares, n(2n - 1)(2n + 1) / 3, with n = 50: 50 x 99 x 101 / 3 = 166,650. See performance.

Part 4: Mixed challenges

Exercise 13: A faceted plot

Using mtcars, draw mpg against hp as points colored by number of cylinders, split into two panels by transmission, with a title that states a finding.

R
library(ggplot2)
ggplot(mtcars, aes(hp, mpg, color = factor(cyl))) +
  geom_point(size = 2.5) +
  facet_wrap(~ am, labeller = labeller(am = c("0" = "Automatic", "1" = "Manual"))) +
  scale_color_viridis_d() +
  labs(title = "More horsepower, fewer miles per gallon",
       x = "Horsepower", y = "Miles per gallon", color = "Cylinders") +
  theme_minimal()

You should see two panels of falling point clouds, where the 8-cylinder cars sit at the high-horsepower, low-mileage end in both. See ggplot2 basics and customizing.

Exercise 14: Word frequencies

Count how often each word appears in "the cat and the hat and the bat" and show the words from most to least frequent.

R
text <- "the cat and the hat and the bat"
freq <- sort(table(strsplit(text, " ")[[1]]), decreasing = TRUE)
freq
#
# the and bat cat hat 
#   3   2   1   1   1 
names(freq)[1]       # "the"

table() counts, sort(decreasing = TRUE) orders; words with equal counts keep their alphabetical order. For real text, lowercase with tolower() and strip punctuation with gsub("[[:punct:]]", "", text) first.

Exercise 15: Vectorized FizzBuzz

For the numbers 1 to 15 print "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both, and the number otherwise, without a loop.

R
n <- 1:15
ifelse(n %% 15 == 0, "FizzBuzz",
  ifelse(n %% 3 == 0, "Fizz",
    ifelse(n %% 5 == 0, "Buzz", n)))
# "1" "2" "Fizz" "4" "Buzz" "Fizz" "7" "8" "Fizz" "Buzz" "11" "Fizz" "13" "14" "FizzBuzz"

Test the most specific case (15) first, or the multiples of 15 will be reported as "Fizz". The result is a character vector because it mixes words and numbers.

Check the numbers in Python

This Python block recomputes the numeric answers above, including the regression on the cars data, so you can verify the R results.

Python Python comparison: checking the numeric answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How did you do?

  • 13-15 solved: you are comfortable with the whole toolkit. Pick a data set that interests you and write your own analysis, like the mtcars project.
  • 8-12 solved: go back to the lessons for the exercises you missed, then redo those without peeking.
  • Fewer than 8: normal at this stage. Re-read the lessons in small pieces and type every example yourself.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why test the multiples of 15 first in the nested ifelse() for FizzBuzz?

    The tests are checked in order. If the multiple-of-3 test came first, 15 would be labeled Fizz.
  2. 2. In Exercise 6, why is P(at least 3) computed as 1 - pbinom(2, ...)?

    'At least 3' means X >= 3, which is everything except X <= 2.
  3. 3. What does the negative intercept in the cars model tell you?

    Extrapolating outside the observed range (speeds 4 to 25 mph) is unreliable; the intercept is just where the line crosses the axis.

Summary

  • You applied strings, regular expressions, dates, statistics, distributions, tests, regression, functional tools, S3 objects, error handling and ggplot2 to small problems.
  • Practice works best when you attempt first, compare second, and then change the problem.
  • Next steps: build your own analysis end to end, package your helper functions, and explore the tidyverse and Quarto for reproducible reports.

Next: Back to the R Programming course