Time Series Analysis
ts Objects
Creating and Plotting Time Series
R's ts() creates time series objects. The forecast package provides auto.arima() for automatic model selection.
library(forecast)
sales <- ts(c(120,135,140,132,150,165,170,155,148,160,175,180), start=c(2023,1), frequency=12)
plot(sales)
decompose(sales) |> plot() # trend + seasonal + remainder
# AirPassengers — monthly international airline passengers 1949-1960
data("AirPassengers")
plot(AirPassengers, main = "Monthly Airline Passengers (1949-1960)",
ylab = "Passengers (thousands)", col = "#1d4ed8", lwd = 2)
# See the code example above and adapt it to your data. # Always check your output with str() and head().
ARIMA Forecasting
auto.arima() automatically selects the best ARIMA model using information criteria. forecast() generates future predictions with confidence intervals.
model <- auto.arima(sales)
summary(model) # model parameters and fit
fc <- forecast(model, h=12) # 12 months ahead
autoplot(fc) + labs(title='12-Month Sales Forecast')
# ARIMA forecast: fit model and predict next 24 months
library(forecast)
model_arima <- auto.arima(AirPassengers)
model_arima
Series: AirPassengers
ARIMA(2,1,1)(0,1,0)[12]
Coefficients:
ar1 ar2 ma1
0.5960 0.2143 -0.9819
s.e. 0.0888 0.0880 0.0292
sigma^2 = 132.3: log likelihood = -504.92
AIC=1017.84 AICc=1018.17 BIC=1029.35# Plot 24-month forecast with 80% and 95% confidence intervals
forecast_24 <- forecast(model_arima, h = 24)
autoplot(forecast_24) +
labs(title = "AirPassengers — 24-Month ARIMA Forecast",
x = "Year", y = "Passengers (thousands)") +
theme_minimal()
# See the code example above and adapt it to your data. # Always check your output with str() and head().