Time Series in R
Order carries information that a table throws away
Cross-sectional data can be shuffled without loss; time series cannot. The sequence encodes trend, seasonality, momentum, and the tendency of shocks to persist, and a modelling approach that ignores order will happily fit noise and call it signal. The first decision in any temporal problem is therefore what the index means: how often observations arrive, what counts as a missing period, and whether the interval is uniform.
Once the index is right, the workflow narrows to a few durable steps: decompose to understand the shape, test whether the series is stationary, choose a model that matches what remains, and check that the leftovers behave like noise. Forecasts built on that sequence are usually defensible; forecasts built without it usually are not.
- Construct ts objects with explicit start and frequency.
- Decompose before modelling so trend and seasonality are visible.
- Test stationarity, difference until it holds, then forecast and check residuals.
Prerequisites
- !R vectors, plotting, and the pipe operator
- !Mean, variance, and correlation concepts
What You'll Learn
- 1Create ts objects with correct start, end, and frequency attributes
- 2Decompose series with classical and STL methods and read the components
- 3Apply ADF and KPSS stationarity tests and difference until the series is stable
- 4Fit ETS and ARIMA models, then evaluate forecasts with holdout accuracy
Constructing ts objects correctly
The ts() constructor attaches three attributes that everything downstream reads: start, frequency, and end. Get frequency wrong and seasonal decomposition will average across the wrong periods, producing a seasonal component that is pure artefact. Monthly data uses frequency twelve, quarterly data four, daily data with weekly seasonality seven.
# Monthly observations beginning January 2022
sales <- ts(c(120, 135, 141, 158, 162, 171,
149, 152, 168, 181, 195, 210,
138, 147, 155, 169, 178, 186),
start = c(2022, 1), frequency = 12)
start(sales); end(sales); frequency(sales)
time(sales) # numeric time index
cycle(sales) # position within the seasonal cycle
# Coerce a data frame column, keeping the ordering explicit
raw <- read.csv("data/monthly_orders.csv")
orders <- ts(raw$orders, start = c(2020, 1), frequency = 12)
# Aggregate daily data to a regular monthly series before modelling
library(dplyr)
library(lubridate)
daily <- read.csv("data/orders_daily.csv", stringsAsFactors = FALSE)
monthly <- daily |>
mutate(month = floor_date(as.Date(date), "month")) |>
group_by(month) |>
summarise(orders = sum(orders), .groups = "drop")
orders_ts <- ts(monthly$orders, start = c(2020, 1), frequency = 12)
plot(sales, main = "Monthly sales", ylab = "Orders")
Two practical warnings. Irregular timestamps must be regularised before ts() â a series with a missing month is not the same as one with a gap that you have imputed, and silently compressing the vector shifts every subsequent seasonal position. And ts() assumes equal spacing, so financial series with trading-day gaps are better handled with a time-aware class or an explicit adjustment for trading days.
Decomposition: trend, season, remainder
Classical decomposition separates a series into a trend, a seasonal pattern that repeats every cycle, and a remainder. Multiplicative decomposition (trend times season times remainder) fits series whose seasonal amplitude grows with the level; additive decomposition fits series where the seasonal swing is constant.
data("AirPassengers")
# Classical decomposition: plot all four panels
add_decomp <- decompose(AirPassengers, type = "additive")
mult_decomp <- decompose(AirPassengers, type = "multiplicative")
plot(mult_decomp)
# STL: robust to outliers, handles changing seasonality
library(forecast)
stl_fit <- stl(AirPassengers, s.window = "periodic", robust = TRUE)
plot(stl_fit)
# Seasonal diagnostics
ggseasonplot(AirPassengers, year.labels = TRUE)
ggsubseriesplot(AirPassengers)
gglagplot(AirPassengers)
# Extract components as plain vectors
trend <- stl_fit$time.series[, "trend"]
seasonal <- stl_fit$time.series[, "seasonal"]
remainder <- stl_fit$time.series[, "remainder"]
STL is usually the better first look because it does not require equal seasonal windows, tolerates a few extreme observations, and lets the seasonal pattern evolve slowly across years. The remainder column is the real product of decomposition: if it still shows visible structure, the model you fit next will be missing a term, and if it looks like white noise, you have learned how much of the series no deterministic component can explain.
Stationarity: two tests that disagree productively
Stationarity means the mean and variance of the series do not drift over time and the autocorrelation structure depends only on lag. ARIMA assumes it, so the series must be differenced until it holds. The ADF test takes the pessimistic stance that a unit root is present unless disproved; KPSS takes the opposite stance that the series is stationary unless disproved, and reading them together is more informative than either alone.
library(tseries)
adf.test(AirPassengers) # H0: unit root (non-stationary)
kpss.test(AirPassengers) # H0: stationary
# Difference until both tests are happy
d1 <- diff(AirPassengers, differences = 1)
adf.test(d1) # likely stationary after one difference
kpss.test(d1)
# Seasonal difference when annual pattern dominates
d_seasonal <- diff(AirPassengers, lag = 12)
plot(d_seasonal)
# Autocorrelation structure before choosing orders
par(mfrow = c(2, 1))
acf(diff(AirPassengers), main = "ACF of first difference")
pacf(diff(AirPassengers), main = "PACF of first difference")
par(mfrow = c(1, 1))
Interpreting the four possible outcomes is worth memorising. Reject ADF and fail to reject KPSS: the series needs differencing. Fail to reject ADF and reject KPSS: trend-stationary, so detrend rather than difference. Reject both: the tests disagree, usually because of structural breaks, and the series needs investigating before modelling. Fail to reject both: proceed. Differencing more times than necessary removes signal and injects negative autocorrelation, so stop as soon as both tests pass.
Smoothing when you need a level, not a model
Smoothing methods are the lightweight end of forecasting. A moving average removes short-term noise to expose trend; exponential smoothing weights recent observations more heavily and needs only the previous smoothed value, which makes it cheap to run recursively.
library(forecast)
# Moving averages of different widths
ma12 <- ma(AirPassengers, order = 12)
ma3 <- ma(AirPassengers, order = 3)
plot(AirPassengers, main = "Series with 3- and 12-period moving averages")
lines(ma3, col = "steelblue", lwd = 2)
lines(ma12, col = "tomato", lwd = 2)
# Simple exponential smoothing: level only
ses_fit <- ses(AirPassengers, h = 12, alpha = 0.3)
summary(ses_fit)
# Holt: level plus trend
holt_fit <- holt(AirPassengers, h = 12)
# Holt-Winters: level, trend, and seasonality
hw_fit <- hw(AirPassengers, h = 12, seasonal = "multiplicative")
autoplot(hw_fit) + autolayer(fitted(hw_fit), series = "Fitted")
# State-space formulation with automatic parameter selection
ets_fit <- ets(AirPassengers)
summary(ets_fit)
The ETS naming convention (error, trend, seasonal) makes the model explicit: ANN is simple exponential smoothing, AAN adds a trend, and MAM matches multiplicative Holt-Winters. ets() selects among them automatically using information criteria, and the resulting fitted components can be inspected directly rather than estimated by hand.
ARIMA and choosing the orders
ARIMA combines three ideas: differencing to reach stationarity (the d term), an autoregressive term that regresses on its own lags (p), and a moving-average term that regresses on past forecast errors (q). The ACF and PACF plots after differencing give the initial read â a PACF that cuts off after lag p suggests an AR(p), an ACF that cuts off after lag q suggests an MA(q) â and auto.arima() then searches the neighbourhood systematically.
library(forecast)
# Automatic selection with a defensible search
auto_fit <- auto.arima(AirPassengers,
seasonal = TRUE,
stepwise = FALSE,
approximation = FALSE)
summary(auto_fit)
coef(auto_fit)
# Manual specification informed by ACF/PACF
manual_fit <- Arima(AirPassengers,
order = c(2, 1, 1),
seasonal = list(order = c(1, 1, 1), period = 12))
AIC(auto_fit, manual_fit)
# Residual diagnostics: the model is done only when these pass
checkresiduals(auto_fit)
Box.test(residuals(auto_fit), lag = 24, type = "Ljung-Box")
checkresiduals() is the gate. You want residuals with no significant autocorrelation, a distribution close to normal, and constant variance; a significant Ljung-Box statistic means predictable structure remains in the leftovers and the forecast intervals will be too narrow. Comparing a manual fit against the automatic one with AIC is a useful discipline â if your specification cannot beat the search on the same data, use the search and explain its orders.
Evaluating forecasts honestly
In-sample fit flatters every model. The reliable test is a holdout: fit on the training window, forecast the last h observations you set aside, and compare against what actually happened. MASE is the metric to quote when the series has a unit or a scale that makes RMSE uninterpretable on its own.
library(forecast)
# Time-ordered split: never shuffle a series
h <- 12
train <- window(AirPassengers, end = c(1959, 12))
test <- window(AirPassengers, start = c(1960, 1))
ets_fc <- forecast(ets(train), h = h)
arima_fc <- forecast(auto.arima(train), h = h)
naive_fc <- naive(train, h = h)
accuracy(ets_fc, test)
accuracy(arima_fc, test)
accuracy(naive_fc, test)
# Compare against the seasonal-naive benchmark explicitly
snaive_fc <- snaive(train, h = h)
accuracy(snaive_fc, test)
autoplot(window(AirPassengers, start = 1955)) +
autolayer(ets_fc, series = "ETS", PI = FALSE) +
autolayer(arima_fc, series = "ARIMA", PI = FALSE) +
autolayer(test, series = "Actual")
| Metric | What it measures | Use it when |
|---|---|---|
| MAE | mean absolute error in original units | the unit itself is meaningful |
| RMSE | error with large mistakes penalised quadratically | overshooting is much worse than undershooting |
| MAPE | percentage error | comparing across series of different scale |
| MASE | error relative to a seasonal-naive forecast | you need a scale-free benchmark |
| Coverage | share of actuals inside the interval | interval calibration is the requirement |
Always include the seasonal-naive benchmark. A model that beats nothing has demonstrated nothing, and MASE below one is the clean statement that the model beats the dumbest reasonable alternative.
Mistakes that produce confident wrong forecasts
Common Mistakes
Shuffling rows before splitting train and test
Fix: Split on time order; random splits leak the future into training and inflate accuracy dramatically.
Setting frequency = 1 on seasonal data
Fix: Declare the true cycle (12 for monthly, 4 for quarterly) or decomposition and seasonal ARIMA cannot work.
Differencing until the ADF test passes without checking KPSS
Fix: Read both tests; over-differencing creates negative autocorrelation and unstable intervals.
Accepting a model while Ljung-Box rejects residual independence
Fix: Increase p or q, add seasonal terms, or try another class until residuals look like noise.
Reporting in-sample R-squared as forecast quality
Fix: Quote holdout accuracy against a seasonal-naive benchmark instead.
Extrapolating a trend without questioning its stability
Fix: Check whether the trend has changed across the sample and widen intervals for long horizons.
Modelling irregular timestamps with ts()
Fix: Regularise the index first, decide how gaps are filled, and document the imputation.
Practices that make forecasts reviewable
Best Practices
- Plot and decompose the series before fitting anything.
- State the frequency, horizon, and aggregation level up front.
- Use both ADF and KPSS, and record the differencing decisions you made.
- Always benchmark against seasonal-naive accuracy and report MASE.
- Check residuals with Ljung-Box and the default diagnostic plot before publishing intervals.
- Keep the holdout window untouched by model selection.
- Re-fit on a rolling basis and track accuracy over time to catch drift.
Key takeaways
Key Takeaways
- ts() stores start and frequency, and a wrong frequency corrupts every seasonal calculation after it.
- Decomposition makes trend and seasonality explicit and hands you a remainder to judge whether structure remains.
- ADF and KPSS test opposite hypotheses, so reading both localises the problem instead of just failing one test.
- Exponential smoothing covers level, trend, and season variants; ets() selects among them automatically.
- ARIMA orders come from ACF and PACF after differencing, then get refined by search and AIC.
- Residual diagnostics, especially Ljung-Box, decide when a model is finished.
- Holdout accuracy against a seasonal-naive benchmark is the only honest measure of forecast quality.
Where to go next
- R Machine Learning with caret â cross-validation machinery that also applies to temporal splits.
- R Statistical Functions â the descriptive toolkit for examining a series first.
- R Linear Regression â regression with time as an explicit predictor, and its autocorrelation trap.