Skip to main content
R Programming
CHAPTER 21 Beginner

Time Series Analysis in R

Updated: May 18, 2026
5 min read

# CHAPTER 21

Time Series Analysis in R

1. Chapter Introduction

Time series data captures how variables change over time — stock prices, monthly sales, quarterly GDP. R's rich time series ecosystem (ts, xts, forecast, fable) provides everything from basic trend analysis to advanced ARIMA forecasting.

2. Time Series Objects

r
1234567891011121314151617181920212223242526272829303132
library(forecast)
library(ggplot2)
library(dplyr)

# Create ts object
# ts(data, start, frequency)
# frequency: 12=monthly, 4=quarterly, 52=weekly, 365=daily

monthly_sales <- ts(
  data      = c(120, 135, 128, 142, 156, 168, 145, 162, 175, 188, 195, 220,
                 130, 148, 142, 158, 172, 184, 160, 178, 192, 205, 212, 245),
  start     = c(2023, 1),   # Year 2023, January
  frequency = 12            # Monthly
)

# Properties
start(monthly_sales)    # 2023 1
end(monthly_sales)      # 2024 12
frequency(monthly_sales) # 12
length(monthly_sales)   # 24

# Plot
autoplot(monthly_sales) +
  labs(title="Monthly Sales 2023-2024", x="Time", y="Units Sold") +
  theme_minimal()

# Seasonal plots
ggseasonplot(monthly_sales) +
  labs(title="Seasonal Pattern by Month")

ggsubseriesplot(monthly_sales) +
  labs(title="Monthly Subseries Plot")

3. Decomposition

r
1234567891011121314151617181920212223
# Decompose = Trend + Seasonal + Residual

# Classical decomposition
decomp <- decompose(monthly_sales, type="additive")  # or "multiplicative"
plot(decomp)
# Components:
decomp$trend     # Smooth trend
decomp$seasonal  # Seasonal pattern
decomp$random    # Residuals

# STL decomposition (better — handles changing seasonality)
stl_decomp <- stl(monthly_sales, s.window="periodic")
autoplot(stl_decomp) + theme_minimal()

# Moving averages (manual smoothing)
ma_3  <- ma(monthly_sales, order=3)   # 3-month moving average
ma_12 <- ma(monthly_sales, order=12)  # 12-month (removes seasonality)

autoplot(monthly_sales, series="Original", alpha=0.5) +
  autolayer(ma_3,  series="3-Month MA") +
  autolayer(ma_12, series="12-Month MA") +
  labs(title="Sales with Moving Averages") +
  theme_minimal()

4. Forecasting with ARIMA

r
123456789101112131415161718192021222324252627282930313233
# AUTO-ARIMA — automatically selects best model
model <- auto.arima(monthly_sales, seasonal=TRUE)
summary(model)

# Forecast 12 months ahead
forecast_result <- forecast(model, h=12)
print(forecast_result)

# Plot forecast with confidence intervals
autoplot(forecast_result) +
  labs(title="12-Month Sales Forecast",
       subtitle="80% and 95% prediction intervals",
       x="Time", y="Units Sold") +
  theme_minimal()

# Exponential Smoothing (ETS — handles trend + seasonality)
ets_model    <- ets(monthly_sales)
ets_forecast <- forecast(ets_model, h=12)
autoplot(ets_forecast) + theme_minimal()

# Model accuracy
accuracy(model)
# Shows: ME, RMSE, MAE, MAPE, MASE
cat(sprintf("MAPE: %.2f%% (Mean Absolute Percentage Error)\n",
             accuracy(model)[5]))

# Forecast specific values
cat("\n12-Month Forecast:\n")
for (i in 1:12) {
  cat(sprintf("  Month %d: %.0f (80%% CI: %.0f - %.0f)\n",
               i, forecast_result$mean[i],
               forecast_result$lower[i,1], forecast_result$upper[i,1]))
}

5. Common Mistakes

  • Seasonal data without frequency specification: ts(data, frequency=1) doesn't capture seasonality. Always set frequency=12 for monthly, frequency=4 for quarterly.
  • Forecasting without checking stationarity: ARIMA requires stationary series. auto.arima() handles this automatically, but manual ARIMA requires ndiffs(x) to determine differencing needed.

6. MCQs

Question 1

ts(x, start=c(2023,1), frequency=12) creates?

Question 2

decompose() splits time series into?

Question 3

auto.arima() does?

Question 4

MAPE measures?

Question 5

Moving average with order=12 on monthly data?

Question 6

forecast(model, h=12) forecasts?

Question 7

ETS model handles?

Question 8

Prediction interval is?

Question 9

ggseasonplot() shows?

Question 10

Additive vs multiplicative decomposition: use multiplicative when?

7. Interview Questions

  • Q: What is ARIMA and what do the p, d, q parameters represent?
  • Q: How do you decompose a time series in R?

8. Summary

Time series in R: ts(data, start, frequency) object. Decompose: decompose() (classical), stl() (robust). Moving averages: ma() for smoothing. Forecasting: auto.arima() (best model selection), ets() (exponential smoothing). Evaluate: accuracy() → MAPE. Always specify correct frequency. Use 80%/95% prediction intervals for uncertainty communication.

9. Next Chapter Recommendation

In Chapter 22: Exploratory Data Analysis (EDA), we systematically explore any dataset to uncover patterns, relationships, and anomalies before modeling.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·