R Time Series Analysis — Analyzing Temporal Data
Learning Objectives
By the end of this tutorial, you will be able to:
- Create and manipulate time series objects
- Decompose time series into trend, seasonal, and residual components
- Apply smoothing methods (moving averages, exponential smoothing)
- Build ARIMA models for forecasting
- Evaluate forecast accuracy
Creating Time Series Objects
# ts() — base R time series
ts_data <- ts(mtcars$mpg, start = 1974, frequency = 1)
print(ts_data)
# Monthly data
monthly <- ts(1:24, start = c(2022, 1), frequency = 12)
# Quarterly data
quarterly <- ts(1:8, start = c(2022, 1), frequency = 4)
# Plot
plot(monthly, main = "Monthly Time Series")
Decomposition
# Load AirPassengers dataset
data("AirPassengers")
# Classical decomposition
decomp <- decompose(AirPassengers, type = "multiplicative")
plot(decomp)
# STL decomposition (more robust)
library(forecast)
stl_decomp <- stl(AirPassengers, s.window = "periodic")
plot(stl_decomp)
# Seasonal plot
ggseasonplot(AirPassengers)
ggsubseriesplot(AirPassengers)
Smoothing Methods
Moving Averages
library(forecast)
# Simple moving average
ma(AirPassengers, order = 12)
# Weighted moving average
weighted.mean(tail(AirPassengers, 12), 1:12/sum(1:12))
# Plot
plot(AirPassengers, main = "AirPassengers with Moving Average")
lines(ma(AirPassengers, 12), col = "red", lwd = 2)
Exponential Smoothing
# Simple exponential smoothing
model_ses <- ses(AirPassengers, h = 12)
plot(model_ses)
# Holt's method (trend)
model_holt <- holt(AirPassengers, h = 12)
plot(model_holt)
# Holt-Winters (trend + seasonality)
model_hw <- hw(AirPassengers, h = 12, seasonal = "multiplicative")
plot(model_hw)
ARIMA Models
Auto ARIMA
library(forecast)
# Automatic ARIMA selection
model <- auto.arima(AirPassengers)
summary(model)
# Forecast
fc <- forecast(model, h = 24)
plot(fc)
# Accuracy
accuracy(model)
Manual ARIMA
# Specify ARIMA order
model <- Arima(AirPassengers, order = c(2, 1, 1), seasonal = c(1, 1, 1))
summary(model)
# Check residuals
checkresiduals(model)
Forecasting
library(forecast)
# ARIMA forecast
model <- auto.arima(AirPassengers)
fc <- forecast(model, h = 12)
# ETS (Error, Trend, Seasonal) model
model_ets <- ets(AirPassengers)
fc_ets <- forecast(model_ets, h = 12)
# Compare
plot(fc)
lines(fc_ets$mean, col = "red")
# Accuracy metrics
accuracy(fc)
Stationarity
library(tseries)
# Augmented Dickey-Fuller test
adf.test(AirPassengers)
# KPSS test
kpss.test(AphAssengers)
# Differencing to achieve stationarity
diff_data <- diff(AirPassengers, differences = 1)
plot(diff_data)
# ACF and PACF
par(mfrow = c(2, 1))
acf(AirPassengers, main = "ACF")
pacf(AirPassengers, main = "PACF")
par(mfrow = c(1, 1))
Practical Examples
Example 1: Stock Price Forecasting
library(quantmod)
# Get stock data
getSymbols("AAPL", src = "yahoo", from = "2020-01-01")
# Use closing prices
prices <- Cl(AAPL)
# Forecast
model <- auto.arima(prices)
fc <- forecast(model, h = 30)
plot(fc, main = "AAPL Stock Price Forecast")
Example 2: Sales Forecasting
# Monthly sales data
set.seed(42)
sales <- ts(cumsum(rnorm(120, 100, 20)) + sin(1:120/12 * 2 * pi) * 500,
start = c(2014, 1), frequency = 12)
# Decompose
decomp <- stl(sales, s.window = "periodic")
plot(decomp)
# Forecast
model <- auto.arima(sales)
fc <- forecast(model, h = 24)
plot(fc)
Practice Exercises
Exercise 1: US Gas Consumption
Forecast US gas consumption using the WWWusage dataset.
Solution
library(forecast)
# Load data
data("WWWusage")
# Plot
plot(WWWusage, main = "WWW Usage")
# Auto ARIMA
model <- auto.arima(WWWusage)
summary(model)
# Forecast
fc <- forecast(model, h = 10)
plot(fc)
# Accuracy
accuracy(model)
Key Takeaways
ts()creates time series objects with start, frequency- Decomposition separates trend, seasonal, and residual components
- Moving averages smooth short-term fluctuations
- Exponential smoothing gives more weight to recent observations
- ARIMA models handle non-stationary data with differencing
auto.arima()automatically selects best model- Always check residuals for white noise
- Use
forecast()to predict future values
Next: Learn about R Machine Learning with caret — predictive modeling.