Mathew K Analytics

Lesson 8 · R Programming: Zero to Expert

Time Series Forecasting in R: ETS, ARIMA & Honest Accuracy (Full Course) | R 108

Video 8 of R Programming: Zero to Expert. Trends, seasons, smoothing, ARIMA and honest forecasts. R script: 08timeseries.R. Download it from this page and…

⬇ 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

Time Series Analysis and Forecasting in R#

Video 8 of R Programming: Zero to Expert.

Trends, seasons, smoothing, ARIMA and honest forecasts.

R script: 08_time_series.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).

Setup#

library(tidyverse)
library(forecast)

The tidyverse lists its core packages as usual, and forecast loads quietly.

What makes time series different#

Order matters, the past informs the future, and we never peek ahead.

The ts object#

AirPassengers

R prints the series as a calendar: one row per year from nineteen forty nine to nineteen sixty, one column per month. Even in raw numbers you can see two things. Each row is higher than the one before, and within each year the summer months, July and August, are the busiest.

class(AirPassengers)
start(AirPassengers)
end(AirPassengers)
frequency(AirPassengers)
length(AirPassengers)

The class is t s. It starts in nineteen forty nine, period one, which means January, and ends in nineteen sixty, period twelve, December. The frequency is twelve, so these are monthly data, and there are one hundred and forty four observations, twelve years of twelve months.

sales <- c(120, 132, 101, 134, 190, 230, 210, 205, 170, 160, 140, 180,
           130, 145, 115, 150, 200, 245, 225, 220, 185, 170, 150, 195)
sales_ts <- ts(sales, start = c(2023, 1), frequency = 12)
sales_ts

Our sales now print as a neat calendar, with twenty twenty three on the first row and twenty twenty four on the second. You can see the same summer peak in June each year.

time(sales_ts)[1:3]
cycle(sales_ts)[1:14]

January twenty twenty three is two thousand and twenty three point zero, February is point zero eight three, one twelfth of a year later, and so on. cycle counts one to twelve and then starts again at one, so the thirteenth value is January again.

window(sales_ts, start = c(2024, 6), end = c(2024, 9))

Just four months: two hundred and forty five, two hundred and twenty five, two hundred and twenty, and one hundred and eighty five.

Plot first, always#

autoplot(AirPassengers) +
  labs(title = "Monthly airline passengers",
       y = "Passengers (thousands)", x = NULL)

Three things jump out. A strong upward trend. A repeating yearly pattern, with peaks every summer. And the swings get bigger as the series grows. Trend, seasonality and changing variance. Almost every business series has some mix of these, and today we learn to handle each one.

Seasonal plots#

ggseasonplot(AirPassengers, year.labels = TRUE) +
  labs(title = "Season plot", y = "Passengers")

Each line is one year, and the later years sit higher. Every year rises to a peak in July and August, then falls into November. The shape repeats, which is what seasonality means.

ggsubseriesplot(AirPassengers) +
  labs(title = "Subseries plot", y = "Passengers")

Each mini line shows how one month changed over the years, and the blue bar marks that month's average. July and August have the highest averages, November the lowest.

Taking a series apart: decomposition#

dec <- decompose(AirPassengers, type = "multiplicative")
autoplot(dec)

Four panels. The data at the top, then a smooth rising trend, a seasonal pattern that repeats exactly each year, and the remainder, the noise that is left. In a multiplicative model the seasonal part is a multiplier around one. A value of one point two means that month is about twenty percent above the trend.

round(dec$figure, 2)

November is the quietest month, at about zero point eight, twenty percent below trend. July and August are the busiest, at about one point two three and one point two two, more than twenty percent above trend.

fit_stl <- stl(log(AirPassengers), s.window = "periodic")
autoplot(fit_stl)

The same story on the log scale: a steady trend, a stable seasonal shape, and a small remainder. S T L is more flexible than decompose, and it can also let the season change slowly over time.

ap_sa <- seasadj(fit_stl)
autoplot(exp(ap_sa)) + labs(title = "Seasonally adjusted passengers",
                            y = "Passengers")

Without the seasonal zigzag, the underlying growth is easy to read. A seasonally adjusted series answers the question: is business really growing, or is it just summer?

Taming growing swings with logs#

autoplot(log(AirPassengers)) +
  labs(title = "Log of passengers", y = "log(passengers)")

On the log scale the seasonal swings are the same size from start to end, and the trend is almost a straight line. Many models assume constant variance, so this makes them much happier.

lambda <- BoxCox.lambda(AirPassengers)
lambda

The estimate is about minus zero point three. That is not exactly zero, but it is close, and a log is much easier to explain, so most analysts would simply use the log here.

Moving averages#

ma12 <- ma(AirPassengers, order = 12)
autoplot(AirPassengers, series = "Data") +
  autolayer(ma12, series = "12-month MA") +
  labs(y = "Passengers", colour = NULL)

The moving average is a smooth rising line through the middle of the seasonal zigzag. It is missing for the first six and last six months, because a centred average needs values on both sides. That is what the warning about removed rows is telling us.

head(ma12, 9)

Six N As, then the first averages, starting at about one hundred and twenty six point eight in July nineteen forty nine.

Lags, differences and autocorrelation#

x <- ts(c(5, 7, 6, 9, 12, 11))
stats::lag(x, -1)
diff(x)
diff(x, lag = 2)

The lagged series has the same values, but now starts at time two instead of one. It has been shifted one step later. diff gives two, minus one, three, three and minus one: the step by step changes. And the two step changes are one, two, six and two. Notice each diff is one or two values shorter than the original.

ggAcf(AirPassengers, lag.max = 36) +
  labs(title = "ACF of airline passengers")

Every bar is tall and positive, and they shrink only slowly. That slow decay is the signature of a trend. Small bumps at lags twelve, twenty four and thirty six show the yearly season. The blue dashed lines mark the range we would expect from pure noise. Bars beyond them are real patterns.

gglagplot(sales_ts, lags = 4, do.lines = FALSE)

Each panel compares the series with itself one, two, three and four months earlier. The colours mark the months. The lag one panel shows a clear upward cloud: a busy month tends to follow a busy month.

ap_diff <- diff(log(AirPassengers), lag = 12)
autoplot(ap_diff) + labs(title = "Year-on-year change (log)")

The trend and the season have disappeared. What remains wanders around a level of roughly zero point one, about ten percent growth per year. A series like this, without trend or season, is called stationary.

ndiffs(log(AirPassengers))
nsdiffs(log(AirPassengers))

Both say one. One ordinary difference and one seasonal difference are enough to make the log series stationary.

Train and test: forecasting honestly#

Hold back the latest data, forecast it, compare.

train <- window(AirPassengers, end = c(1958, 12))
test <- window(AirPassengers, start = c(1959, 1))
h <- length(test)
h

The test set has twenty four months.

Benchmark forecasts#

f_mean <- meanf(train, h = h)
f_naive <- naive(train, h = h)
f_snaive <- snaive(train, h = h)
f_drift <- rwf(train, h = h, drift = TRUE)
autoplot(window(AirPassengers, start = 1955)) +
  autolayer(f_mean, series = "Mean", PI = FALSE) +
  autolayer(f_naive, series = "Naive", PI = FALSE) +
  autolayer(f_snaive, series = "Seasonal naive", PI = FALSE) +
  autolayer(f_drift, series = "Drift", PI = FALSE) +
  labs(y = "Passengers", colour = "Forecast")

The mean forecast sits far too low. Naive and drift are flat or gently rising lines that miss the season. Seasonal naive copies last year, so it has the right shape but sits a little low, because it ignores the growth.

Measuring accuracy#

accuracy(f_snaive, test)

The table has a training set row and a test set row. On the test set, seasonal naive misses by about seventy one thousand passengers per month on average, an M A P E of about fifteen and a half percent. The training row shows how well the method fits the past. The test row is the honest one.

bench <- list(Mean = f_mean, Naive = f_naive,
              SNaive = f_snaive, Drift = f_drift)
map_dfr(bench, \(f) {
  a <- accuracy(f, test)["Test set", ]
  tibble(RMSE = a["RMSE"], MAE = a["MAE"], MAPE = a["MAPE"])
}, .id = "method")

The mean method is terrible, with an R M S E over two hundred and a forty four percent error. Naive and drift do better, and seasonal naive wins clearly, with an R M S E of seventy seven and an M A P E of fifteen and a half percent. So every model from now on must beat seventy seven.

Exponential smoothing#

f_ses <- ses(train, h = h)
f_holt <- holt(train, h = h)
f_hw <- hw(train, h = h, seasonal = "multiplicative")
accuracy(f_hw, test)["Test set", c("RMSE", "MAE", "MAPE")]

Holt Winters scores an R M S E of about thirty seven and an M A P E of just over seven percent. That is half the error of the best benchmark.

fit_ets <- ets(train)
fit_ets

ets chose an E T S model with multiplicative errors, an additive damped trend, and a multiplicative season. The A d means damped: the trend is expected to flatten out in the future. Below are the smoothing parameters and the starting values, and A I C values, which ets used to choose between candidate models.

f_ets <- forecast(fit_ets, h = h)
accuracy(f_ets, test)["Test set", c("RMSE", "MAE", "MAPE")]

On the test set this automatic model scores an R M S E of about seventy two and a half. The damped trend flattens too early, while passenger numbers kept climbing. Automatic is not always better than a sensible manual choice.

ARIMA#

AR = autoregressive (past values)

I = integrated (differencing)

MA = moving average (past errors)

fit_arima <- auto.arima(train, lambda = 0)
fit_arima

auto arima chose an ARIMA zero one one, zero one one, with period twelve, on the log scale. That is one ordinary difference and one seasonal difference, plus one moving average term of each kind. Fun fact: this exact model is so famous for this dataset that it is called the airline model.

f_arima <- forecast(fit_arima, h = h)
accuracy(f_arima, test)["Test set", c("RMSE", "MAE", "MAPE")]

ARIMA scores an R M S E of about forty three and an M A P E of about eight and a half percent. Far better than the benchmarks.

checkresiduals(fit_arima)

Three panels: the residuals over time, their autocorrelations, and a histogram. The residuals look like random noise, with almost no bars outside the blue lines. The Ljung Box test has a p value of about zero point five six. A large p value means we cannot find any pattern left in the residuals, which is exactly what we want.

inside <- test >= f_arima$lower[, "95%"] &
  test <= f_arima$upper[, "95%"]
mean(inside)

The answer is one, so all twenty four test months fell inside the ninety five percent interval. We would expect about ninety five percent, so this interval is honest, if anything a little cautious.

Comparing every model#

models <- list(SNaive = f_snaive, HoltWinters = f_hw,
               ETS = f_ets, ARIMA = f_arima)
scores <- map_dfr(models, \(f) {
  a <- accuracy(f, test)["Test set", ]
  tibble(RMSE = a["RMSE"], MAPE = a["MAPE"])
}, .id = "model")
scores |> arrange(RMSE)

Holt Winters wins, with an R M S E of about thirty seven, then ARIMA at about forty three. The automatic E T S model comes third, and seasonal naive is last.

autoplot(window(AirPassengers, start = 1957)) +
  autolayer(f_ets, series = "ETS", PI = FALSE) +
  autolayer(f_arima, series = "ARIMA", PI = FALSE) +
  labs(y = "Passengers", colour = "Model")

Both models follow the seasonal shape of the last two years closely, a big improvement on the benchmarks. Their lines sit close to the black data.

Regression with trend and season#

fit_lm <- tslm(log(train) ~ trend + season)
summary(fit_lm)$r.squared
coef(fit_lm)[c("trend", "season7", "season11")]

R squared is about zero point nine eight. Trend and season together explain ninety eight percent of the variation in log passengers. The trend coefficient is about zero point zero one one, so passengers grow about one percent per month. July is about zero point two nine above January on the log scale, and November about zero point one four below.

f_lm <- forecast(fit_lm, h = h)
f_lm_back <- exp(f_lm$mean)
sqrt(mean((test - f_lm_back)^2))

The regression scores an R M S E of about forty seven. Not quite as good as Holt Winters or ARIMA, but far better than the benchmarks, with a model anyone can understand.

Combining forecasts#

f_combo <- (f_hw$mean + f_arima$mean) / 2
sqrt(mean((test - f_combo)^2))

The average scores an R M S E of about forty. That is better than ARIMA alone, and close to the winner, without us having to know in advance which model would win.

Time series cross-validation#

Many small tests instead of one big one.

snaive_fun <- function(y, h) snaive(y, h = h)
e_snaive <- tsCV(log(AirPassengers), snaive_fun, h = 1)
drift_fun <- function(y, h) rwf(y, h = h, drift = TRUE)
e_drift <- tsCV(log(AirPassengers), drift_fun, h = 1)
c(snaive = sqrt(mean(e_snaive^2, na.rm = TRUE)),
  drift = sqrt(mean(e_drift^2, na.rm = TRUE)))

For one step ahead forecasts, the drift method has the smaller error, about zero point one one on the log scale, against zero point one three for seasonal naive. That is a useful lesson. Which method is best depends on the horizon. One month ahead, last month is very informative. Twenty four months ahead, the seasonal pattern matters more.

e12 <- tsCV(log(AirPassengers), snaive_fun, h = 12)
rmse_by_h <- sqrt(colMeans(e12^2, na.rm = TRUE))
round(rmse_by_h, 3)

For seasonal naive the error barely grows, from about zero point one three five one month ahead to about zero point one three seven twelve months ahead. That makes sense: up to a year ahead, it always copies a value from last year, so every horizon is equally hard for it. For most other methods, error rises clearly with the horizon. Run this check with your own models before promising a long range forecast.

Cleaning a series: outliers and gaps#

messy <- sales_ts
messy[5] <- 900
messy[15] <- NA
tsoutliers(messy)

It flags position five, our fake spike, and suggests one hundred and eighty two instead of nine hundred. It also flags January and March of twenty twenty three, the first and third values. With only two years of data, the method is unsure what normal looks like. Always review flags before accepting them.

cleaned <- tsclean(messy)
round(cbind(messy, cleaned, original = sales_ts)[c(5, 15), ])

The spike of nine hundred became one hundred and eighty two, close to the true one hundred and ninety. The missing March became one hundred and forty eight, while the truth was one hundred and fifteen. Filling a gap can only guess from the neighbours. It cannot know that March was a dip.

Forecasting the future, with uncertainty#

final <- auto.arima(AirPassengers, lambda = 0)
fc <- forecast(final, h = 24, level = c(80, 95))
autoplot(fc) + labs(y = "Passengers")

The dark blue line is the forecast, continuing the trend and the season. The shaded bands are the intervals: darker for eighty percent and lighter for ninety five. They widen as we look further ahead, because the future is less certain.

head(as_tibble(fc), 3)

Each row is a month, with the point forecast and the lower and upper limits of both intervals. For January nineteen sixty one the forecast is about four hundred and fifty, with a ninety five percent range from about four hundred and nineteen to four hundred and eighty four.

fc_df <- tibble(
  month = seq(ymd("1961-01-01"), by = "month", length.out = 24),
  forecast = round(as.numeric(fc$mean)),
  low95 = round(as.numeric(fc$lower[, "95%"])),
  high95 = round(as.numeric(fc$upper[, "95%"]))
)
write_csv(fc_df, "passenger_forecast.csv")
head(fc_df, 4)

Each forecast now has a real date. January nineteen sixty one is forecast at four hundred and fifty, with a range of four hundred and nineteen to four hundred and eighty four, and the file is saved in the project folder.

From a data frame to a time series#

set.seed(42)
daily <- tibble(
  date = seq(ymd("2023-01-01"), ymd("2024-12-31"), by = "day"),
  visits = round(200 + 0.15 * seq_along(date) +
                 40 * (wday(date) %in% c(1, 7)) +
                 rnorm(length(date), sd = 15))
)
daily

Seven hundred and thirty one rows, one per day, because twenty twenty four was a leap year. The first of January twenty twenty three was a Sunday, so it starts with a high value.

monthly <- daily |>
  mutate(month = floor_date(date, "month")) |>
  group_by(month) |>
  summarise(visits = sum(visits))
monthly_ts <- ts(monthly$visits, start = c(2023, 1),
                 frequency = 12)
monthly_ts

Monthly totals grow steadily from about six thousand seven hundred in January twenty twenty three to almost ten thousand in December twenty twenty four. February is lower each year, simply because it is a shorter month.

weekly_pattern <- daily |>
  mutate(day = wday(date, label = TRUE, week_start = 1)) |>
  group_by(day) |>
  summarise(avg = mean(visits))
weekly_pattern

Weekdays average about two hundred and fifty to two hundred and fifty seven visits, while Saturday and Sunday average about two hundred and ninety five. The forty visit weekend boost we built in is clearly visible.

ggplot(weekly_pattern, aes(day, avg)) +
  geom_col(fill = "steelblue") +
  labs(title = "Average visits by weekday", x = NULL, y = "Visits")

Monday to Friday sit at about the same height, while Saturday and Sunday stand clearly taller. Exactly the weekend effect we built in.

daily_roll <- daily |>
  mutate(roll7 = as.numeric(stats::filter(visits, rep(1 / 7, 7),
                                          sides = 1)))
ggplot(daily_roll, aes(date)) +
  geom_line(aes(y = visits), colour = "grey70") +
  geom_line(aes(y = roll7), colour = "firebrick", linewidth = 1) +
  labs(title = "Daily visits with 7-day rolling average", x = NULL)

The grey line jumps around every day, with weekend spikes. The red seven day average cuts through the noise and shows the slow, steady growth. The warning just says the first six days have no average yet.

fc_visits <- forecast(ets(monthly_ts), h = 6)
round(fc_visits$mean)

The forecasts continue the trend: about nine thousand eight hundred and sixty in January twenty twenty five, rising to about ten thousand five hundred by June.

Daily data with two seasons#

visits_msts <- msts(daily$visits, seasonal.periods = c(7, 365.25))
fit_mstl <- mstl(visits_msts)
autoplot(fit_mstl) + labs(title = "Daily visits: trend, weekly and yearly")

The panels show the data, the rising trend, a clear weekly pattern that repeats every seven days, a small, noisy yearly component, and the remainder. Our simulated data had no real yearly season, so that panel is mostly noise, which is the honest answer.

fc_daily <- forecast(fit_mstl, h = 28)
round(as.numeric(head(fc_daily$mean, 7)))

The forecast for the first week of twenty twenty five ranges from about two hundred and ninety to three hundred and fifty visits, and it repeats the weekly rhythm, with the peaks falling on the weekend.

Adding outside information: regression with ARIMA errors#

set.seed(11)
promo <- rep(c(0, 0, 1, 0, 0, 0), length.out = 48)
shop <- ts(500 + 4 * (1:48) + 120 * promo + rnorm(48, sd = 25),
           start = c(2021, 1), frequency = 12)
fit_x <- auto.arima(shop, xreg = promo)
fit_x

The model found a drift of about four per month and a promotion effect of about one hundred and seventeen, very close to the four and one hundred and twenty we built into the data. The ARIMA part handles whatever is left over.

future_promo <- c(0, 0, 1, 0, 0, 0)
fc_x <- forecast(fit_x, xreg = future_promo)
round(fc_x$mean)

The forecast rises gently, from about six hundred and seventy four to seven hundred and six, with a clear jump to about eight hundred and eighteen in March, the promotion month.

Financial series: returns and volatility#

Prices are not forecast like sales. We study their returns.

dax <- EuStockMarkets[, "DAX"]
frequency(dax)
ret <- diff(log(dax))
round(c(mean = mean(ret), sd = sd(ret)) * 100, 3)

R assumes two hundred and sixty trading days per year. The average daily return is a tiny zero point zero six five percent, while the standard deviation is about one percent. Day to day, the noise is fifteen times bigger than the drift, which is why short term prices are so hard to predict.

vol <- zoo::rollapply(ret, 60, sd) * sqrt(260) * 100
autoplot(vol) + labs(title = "DAX 60-day volatility (annualised %)",
                     y = "Volatility %")

Volatility is not constant. It drifts between calm spells below ten percent and nervous spells above twenty, and peaks at over thirty percent in late nineteen ninety seven, during the Asian financial crisis. Risk itself comes in waves.

naive_dax <- naive(dax, h = 20)
autoplot(window(dax, start = 1997.5)) + autolayer(naive_dax) +
  labs(y = "DAX")

The forecast is a flat line at the last price, with intervals that widen quickly. For prices, the naive forecast is famously hard to beat, which is the random walk idea: the best guess for tomorrow is today.

Forecasting many series at once#

stocks <- as.list(as.data.frame(EuStockMarkets))
stock_fc <- map_dfr(stocks, \(p) {
  y <- ts(tail(p, 500))
  f <- forecast(ets(y), h = 10)
  tibble(last = tail(p, 1), day10 = as.numeric(f$mean[10]),
         change_pct = 100 * (day10 / last - 1))
}, .id = "index")
stock_fc |> mutate(across(where(is.numeric), \(x) round(x, 1)))

Four rows, one per index, with the last price, the ten day forecast and the change. The models expect DAX, S M I and C A C to edge up about one percent, and the F T S E to stay flat. Small, cautious forecasts, which is exactly right for prices.

Mini project: Nottingham temperatures#

A pure seasonal series with no trend.

temp_c <- (nottem - 32) * 5 / 9
autoplot(temp_c) + labs(y = "Temperature (C)", x = NULL)

A near perfect seasonal wave: winters average about four degrees and July about sixteen and a half, with no clear trend at all over the twenty years.

t_train <- window(temp_c, end = c(1936, 12))
t_test <- window(temp_c, start = c(1937, 1))
t_fc <- list(SNaive = snaive(t_train, h = 36),
             ETS = forecast(ets(t_train), h = 36),
             Regression = forecast(tslm(t_train ~ season), h = 36))
map_dbl(t_fc, \(f) accuracy(f, t_test)["Test set", "RMSE"]) |>
  round(2)

Seasonal naive misses by about one point seven degrees, E T S by about one point one five, and the seasonal regression by about one point two. Both models beat the benchmark, because they average many years of each month instead of copying a single year.

Common mistakes in forecasting#

  1. Random train/test splits on time series

  2. Judging a model on its training fit

  3. Forgetting the benchmarks

  4. Reporting a single number without intervals

  5. Forecasting far beyond what the data supports

set.seed(3)
idx <- sample(length(AirPassengers), 24)
peek <- AirPassengers
peek[idx] <- NA
filled <- na.interp(peek)
sqrt(mean((filled[idx] - AirPassengers[idx])^2))

An R M S E of about seventeen, less than half of our best honest model. It is too good to be true, and it is not true.

Pause and try#

Exercise 1: seasonal naive vs ETS on the co2 series, last 3 years as test

co2_train <- window(co2, end = c(1994, 12))
co2_test <- window(co2, start = c(1995, 1))
co2_fc <- list(SNaive = snaive(co2_train, h = 36),
               ETS = forecast(ets(co2_train), h = 36))
map_dbl(co2_fc, \(f) accuracy(f, co2_test)["Test set", "RMSE"])

Seasonal naive misses by about three point eight parts per million, because it ignores the steady rise in carbon dioxide. E T S misses by only about zero point eight four, because it models the trend as well as the season. How close was your answer?

Exercise 2: the month with the most accidental deaths, on average

tapply(USAccDeaths, cycle(USAccDeaths), mean) |>
  setNames(month.abb) |>
  sort(decreasing = TRUE) |> head(3)

July is the worst month, with about ten thousand four hundred and fifty deaths on average, then August and June. Summer is the dangerous season, which fits more travel and outdoor activity.

Project: forecast US accidental deaths#

Choose a model on a holdout year, then forecast 1979.

deaths <- USAccDeaths
autoplot(deaths) + labs(title = "US accidental deaths", y = "Deaths")

A strong season, with peaks every July, and a dip in the middle of the decade followed by a recovery. The swings look roughly constant in size, so we can work on the original scale.

d_train <- window(deaths, end = c(1977, 12))
d_test <- window(deaths, start = c(1978, 1))
cands <- list(
  SNaive = snaive(d_train, h = 12),
  ETS = forecast(ets(d_train), h = 12),
  ARIMA = forecast(auto.arima(d_train), h = 12)
)
proj_scores <- map_dfr(cands, \(f) {
  a <- accuracy(f, d_test)["Test set", ]
  tibble(RMSE = a["RMSE"], MAE = a["MAE"], MAPE = a["MAPE"])
}, .id = "model") |> arrange(RMSE)
proj_scores

ARIMA and E T S are almost tied, with R M S Es of about two hundred and ninety, and both beat seasonal naive at about three hundred and forty. Every model has an M A P E under three percent, because this series is very regular.

best_name <- proj_scores$model[1]
best_name
fit_1979 <- if (best_name == "ARIMA") auto.arima(deaths) else ets(deaths)
fc_1979 <- forecast(fit_1979, h = 12)

ARIMA edges ahead on R M S E, so it is our winner, and the code refits ARIMA on all six years. If your versions of the packages put E T S first instead, the same code simply refits E T S.

autoplot(fc_1979) +
  labs(title = "Forecast of US accidental deaths, 1979",
       y = "Deaths", x = NULL)

The forecast repeats the familiar yearly shape, with a summer peak, and the shaded intervals show the range of plausible values for each month.

fc_1979 |>
  as_tibble() |>
  mutate(month = month.abb, .before = 1) |>
  mutate(across(where(is.numeric), round)) |>
  select(month, forecast = `Point Forecast`,
         low95 = `Lo 95`, high95 = `Hi 95`)

Twelve rows, one per month. The forecast peaks in July at around eleven thousand deaths and is lowest in February at about seven and a half thousand, each with its ninety five percent range. That is a table you can paste straight into a planning document.

p_final <- autoplot(fc_1979) +
  labs(title = "US accidental deaths: 1979 forecast", y = "Deaths")
ggsave("deaths_forecast_1979.png", p_final, width = 8, height = 4.5,
       dpi = 150)
file.exists("deaths_forecast_1979.png")

True. The chart is in the project folder, ready to drop into a presentation.

Recap#

  1. ts objects: ts(), start(), frequency(), window()

  2. Plot first: autoplot, season and subseries plots

  3. Decompose: trend + season + remainder; logs for growing swings

  4. Split train/test, beat the benchmarks, measure with accuracy()

  5. ETS and ARIMA, check residuals, forecast with intervals

Found this useful?

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