R Mini Project
In this project you'll analyse two weeks of sales from a small café, one step at a time. It brings together much of the course: reading CSV text, data types and dates, missing values, data frame manipulation, the apply family, functions, S3 classes, graphics and a linear model.
The question the owner wants answered:
Which drinks earn the most, which days are busiest, and do we sell more iced tea when it's hot?
Every step is a complete program that you can run and modify. Each one starts by loading the same small data set, so you can jump to any step.
Step 1: Load the data
The café's till exports one row per day with the temperature and the number of each drink sold. Two values are missing: the thermometer failed on 6 June, and the iced-tea count for 12 June was recorded as -.
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
str(sales)
colSums(is.na(sales))'data.frame': 14 obs. of 5 variables:
$ date : chr "2024-06-03" "2024-06-04" "2024-06-05" "2024-06-06" ...
$ temp_c : int 18 21 24 NA 27 29 26 17 19 23 ...
$ espresso: int 42 40 38 41 45 52 48 39 41 37 ...
$ latte : int 35 33 30 34 29 31 36 37 36 31 ...
$ iced_tea: int 8 14 22 19 31 38 27 6 10 NA ...
date temp_c espresso latte iced_tea
0 1 0 0 1
na.strings turns both the empty field and the dash into NA. Without it, the iced_tea column would have been read as text because of the -.
Step 2: Clean and enrich
Convert the date column to Date, add the weekday, and fill the missing temperature with the average of the neighbouring days. We leave the missing iced-tea count as NA and remember to use na.rm = TRUE later.
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
sales$date <- as.Date(sales$date)
sales$weekday <- factor(format(sales$date, "%a"),
levels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
gap <- which(is.na(sales$temp_c))
sales$temp_c[gap] <- mean(sales$temp_c[c(gap - 1, gap + 1)])
head(sales, 5) date temp_c espresso latte iced_tea weekday
1 2024-06-03 18.0 42 35 8 Mon
2 2024-06-04 21.0 40 33 14 Tue
3 2024-06-05 24.0 38 30 22 Wed
4 2024-06-06 25.5 41 34 19 Thu
5 2024-06-07 27.0 45 29 31 Fri
Making weekday a factor with explicit levels keeps Monday-to-Sunday order in every table and chart.
Step 3: Revenue per drink
Prices live in a named vector. Multiplying each drink column by its price gives revenue; sapply() over the drink names does all three at once:
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
sales$date <- as.Date(sales$date)
prices <- c(espresso = 2.40, latte = 3.60, iced_tea = 3.10)
drinks <- names(prices)
units <- colSums(sales[, drinks], na.rm = TRUE)
revenue <- sapply(drinks, function(d) sum(sales[[d]] * prices[d], na.rm = TRUE))
summary_table <- data.frame(units = units, revenue = round(revenue, 2))
summary_table[order(-summary_table$revenue), ]
cat(sprintf("Total revenue: %.2f\n", sum(revenue))) units revenue
latte 458 1648.8
espresso 611 1466.4
iced_tea 293 908.3
Total revenue: 4023.50
Espresso sells the most cups, but lattes earn the most money because they cost more. Iced tea's total is a slight underestimate, since one day's count is missing.
Step 4: Daily totals and the busiest weekdays
Add a daily revenue column with a matrix product (units × prices), then summarise by weekday with aggregate():
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
sales$date <- as.Date(sales$date)
sales$weekday <- factor(format(sales$date, "%a"),
levels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
prices <- c(espresso = 2.40, latte = 3.60, iced_tea = 3.10)
counts <- as.matrix(sales[, names(prices)])
counts[is.na(counts)] <- 0 # a missing count adds no revenue
sales$revenue <- as.vector(counts %*% prices)
by_day <- aggregate(revenue ~ weekday, data = sales, FUN = mean)
by_day$revenue <- round(by_day$revenue, 2)
by_day
cat("Best day:", as.character(by_day$weekday[which.max(by_day$revenue)]), "\n")
sales[which.max(sales$revenue), c("date", "weekday", "revenue")] weekday revenue
1 Mon 248.50
2 Tue 258.60
3 Wed 233.90
4 Thu 280.60
5 Fri 314.10
6 Sat 360.65
7 Sun 315.40
Best day: Sat
date weekday revenue
13 2024-06-15 Sat 367.1
Weekends are busiest: Saturdays average about 361 in revenue, and the single best day was Saturday 15 June. Wednesdays are the quietest.
Step 5: A reusable report with an S3 class
Wrap the analysis in a function that returns an object of class cafe_report, and give it a print method. Now anyone can produce the report with one call:
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
sales$date <- as.Date(sales$date)
cafe_report <- function(data, prices) {
stopifnot(all(names(prices) %in% names(data)))
counts <- as.matrix(data[, names(prices)])
counts[is.na(counts)] <- 0
daily <- as.vector(counts %*% prices)
structure(list(
from = min(data$date), to = max(data$date),
revenue = colSums(sweep(counts, 2, prices, `*`)),
daily = daily, days = nrow(data)
), class = "cafe_report")
}
print.cafe_report <- function(x, ...) {
cat("Café report", format(x$from, "%d %b"), "to", format(x$to, "%d %b %Y"), "\n")
cat(strrep("-", 36), "\n")
for (d in names(sort(x$revenue, decreasing = TRUE))) {
cat(sprintf("%-10s %10.2f %6.1f%%\n", d, x$revenue[d],
100 * x$revenue[d] / sum(x$revenue)))
}
cat(strrep("-", 36), "\n")
cat(sprintf("%-10s %10.2f\n", "Total", sum(x$revenue)))
cat(sprintf("%-10s %10.2f\n", "Per day", mean(x$daily)))
invisible(x)
}
report <- cafe_report(sales, c(espresso = 2.40, latte = 3.60, iced_tea = 3.10))
reportCafé report 03 Jun to 16 Jun 2024
------------------------------------
latte 1648.80 41.0%
espresso 1466.40 36.4%
iced_tea 908.30 22.6%
------------------------------------
Total 4023.50
Per day 287.39
sweep() multiplies each column of the matrix by the matching price, a handy alternative to looping over columns.
Step 6: Charts
A bar chart of revenue per drink and a line chart of daily sales by drink. Both appear as images under the output:
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
sales$date <- as.Date(sales$date)
prices <- c(espresso = 2.40, latte = 3.60, iced_tea = 3.10)
revenue <- sapply(names(prices), function(d) sum(sales[[d]] * prices[d], na.rm = TRUE))
cols <- c(espresso = "#6f4e37", latte = "#c8a27a", iced_tea = "#e07a5f")
par(mfrow = c(1, 2))
barplot(sort(revenue, decreasing = TRUE), col = cols[names(sort(revenue, decreasing = TRUE))],
main = "Revenue per drink", ylab = "Revenue")
plot(sales$date, sales$espresso, type = "l", lwd = 2, col = cols["espresso"],
ylim = c(0, 60), xlab = "", ylab = "Units sold", main = "Daily units")
lines(sales$date, sales$latte, lwd = 2, col = cols["latte"])
lines(sales$date, sales$iced_tea, lwd = 2, col = cols["iced_tea"])
legend("bottomright", legend = names(cols), col = cols, lwd = 2, bty = "n", cex = 0.8)
cat("Drew 2 charts covering", nrow(sales), "days\n")Drew 2 charts covering 14 days
The iced-tea line has a gap on 12 June: lines() simply skips missing values.
Step 7: Does heat sell iced tea?
Finally, the owner's question. A scatter plot and a linear model of iced-tea sales on temperature; lm() drops the day with a missing count automatically:
csv <- "date,temp_c,espresso,latte,iced_tea
2024-06-03,18,42,35,8
2024-06-04,21,40,33,14
2024-06-05,24,38,30,22
2024-06-06,,41,34,19
2024-06-07,27,45,29,31
2024-06-08,29,52,31,38
2024-06-09,26,48,36,27
2024-06-10,17,39,37,6
2024-06-11,19,41,36,10
2024-06-12,23,37,31,-
2024-06-13,25,40,30,25
2024-06-14,28,46,28,35
2024-06-15,30,55,30,41
2024-06-16,22,47,38,17"
sales <- read.csv(text = csv, na.strings = c("", "-"))
gap <- which(is.na(sales$temp_c))
sales$temp_c[gap] <- mean(sales$temp_c[c(gap - 1, gap + 1)])
fit <- lm(iced_tea ~ temp_c, data = sales)
plot(iced_tea ~ temp_c, data = sales, pch = 19, col = "#e07a5f",
xlab = "Temperature (°C)", ylab = "Iced teas sold", main = "Heat sells iced tea")
abline(fit, lwd = 2)
cat("Days used:", nobs(fit), "\n")
cat(sprintf("Each extra degree: %+.2f iced teas\n", coef(fit)["temp_c"]))
cat(sprintf("R-squared: %.3f\n", summary(fit)$r.squared))
cat(sprintf("Correlation, latte vs. temperature: %.2f\n",
cor(sales$latte, sales$temp_c)))
forecast <- predict(fit, data.frame(temp_c = c(20, 32)))
cat(sprintf("Expected at %d°C: %.0f\n", c(20L, 32L), forecast), sep = "")Days used: 13
Each extra degree: +2.64 iced teas
R-squared: 0.950
Correlation, latte vs. temperature: -0.68
Expected at 20°C: 12
Expected at 32°C: 44
The answer is a clear yes. Each extra degree brings about 2.6 more iced teas, and temperature alone explains 95% of the day-to-day variation (R² = 0.950). Lattes go the other way, with a correlation of -0.68: on hot days people swap hot milk drinks for cold ones. With only 13 days of data, though, the owner should keep collecting before ordering a lot more tea for a 32 °C forecast.
What you built, and ideas to extend it
You read messy CSV text, cleaned it (types, dates, missing values), derived new columns with vectorised arithmetic and a matrix product, summarised by group, wrapped the logic in a function with an S3 print method, drew charts and fitted a model.
Ideas for further practice:
- Add a
summary.cafe_reportmethod that lists the best and worst day. - Reshape the data to long format (one row per day and drink) with
reshape()and redo Step 3 withaggregate(). - Use
t.test()to compare weekend and weekday revenue. - Add a fourth drink with its own price and check that every step still works without code changes.
Test yourself
Why did we pass na.strings = c("", "-") to read.csv()?
- To skip those rows
- So that empty fields and dashes become NA and the columns stay numeric
- To use them as separators
- To remove the header
How does lm() handle the row with a missing iced-tea count?
- It stops with an error
- It treats NA as 0
- It drops that row (na.omit) and fits the rest
- It fills in the mean
What does the S3 method print.cafe_report change?
- How the object is stored
- What is shown when a cafe_report object is printed
- The class of the object
- The data inside the report