Skip to content

R - Time Series Analysis

A time series is a sequence of data points indexed in time order. Common examples include daily stock prices, monthly sales data, or hourly temperature readings. R is exceptionally powerful for time series analysis, offering both classic and modern frameworks.

We will start with the classic ts object, which is fundamental to R. Then, we’ll introduce the modern tsibble framework, which integrates seamlessly with the tidyverse for more flexible and robust analysis.

The ts() function creates a time-series object, which is a vector or matrix with additional attributes for time.

ts(data, start = 1, end = numeric(), frequency = 1, ...)
  • data: A vector or matrix of the observations.
  • start: The time of the first observation. Can be a single number or a vector like c(year, period) (e.g., c(2020, 1) for January 2020).
  • frequency: The number of observations per unit of time. This is a critical parameter: 1 for annual, 4 for quarterly, 12 for monthly, 52 for weekly.

Let’s create a time series object for monthly rainfall data starting from January 2022 and visualize it.

# Load modern libraries for plotting
library(ggplot2)
# Sample monthly rainfall data
rainfall_data <- c(799, 1174, 865, 1334, 635, 918, 685, 998, 784, 985, 882, 1071)
# Create a time series object for monthly data starting in Jan 2022
rainfall_ts <- ts(rainfall_data, start = c(2022, 1), frequency = 12)
# Print the object to see its structure
print(rainfall_ts)
# Visualize the time series
# The autoplot() function from ggplot2 is smart and works well with ts objects
autoplot(rainfall_ts) +
labs(
title = "Monthly Rainfall (2022)",
x = "Time",
y = "Rainfall (mm)"
) +
theme_minimal()

When you print rainfall_ts, you get a nicely formatted output showing the data aligned by month and year:

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2022 799 1175 865 1335 635 918 685 999 784 985 883 1071

The autoplot() command generates a clean line chart, which is the standard way to visualize a time series.

For complex analyses, the tsibble package provides a modern, tidy data structure for time series. A tsibble is a special kind of data frame (tibble) that requires an index (the time variable) and optional key (variables that define unique time series).

# You may need to install these packages first
# install.packages("tsibble")
# install.packages("dplyr")
library(tsibble)
library(dplyr)
# Create two series for different cities
rainfall_city_A <- c(799, 1174, 865, 1334, 635, 918, 685, 998, 784, 985, 882, 1071)
rainfall_city_B <- c(655, 1306, 1323, 1172, 562, 824, 822, 1265, 799, 1105, 1106, 1337)
# Create a data frame (tibble)
rainfall_df <- tibble(
Month = yearmonth(seq(from = as.Date("2022-01-01"), by = "month", length.out = 12)),
City_A = rainfall_city_A,
City_B = rainfall_city_B
)
# Pivot to a long format, which is the 'tidy' way
rainfall_long <- rainfall_df %>%
pivot_longer(cols = c(City_A, City_B), names_to = "City", values_to = "Rainfall")
# Convert to a tsibble, specifying the time index and the key
rainfall_tsibble <- as_tsibble(rainfall_long, index = Month, key = City)
print(rainfall_tsibble)

The tsibble object clearly shows its structure:

# A tsibble: 24 x 3 [1M]
# Key: City [2]
Month City Rainfall
<mth> <chr> <dbl>
1 2022 Jan City_A 799
2 2022 Feb City_A 1175
3 2022 Mar City_A 865
# ... with 21 more rows

Visualizing a tsibble with ggplot2 is natural and powerful. You can easily create facets or color by the key variable.

# Plotting the tsibble automatically handles grouping by the key
ggplot(rainfall_tsibble, aes(x = Month, y = Rainfall, color = City)) +
geom_line() +
labs(
title = "Monthly Rainfall Comparison",
subtitle = "Data for City A vs. City B",
x = "Time",
y = "Rainfall (mm)"
) +
theme_minimal()
  • Decomposition: Break down a time series into its trend, seasonal, and random components using functions like decompose() (base R) or the more advanced STL() from the feasts package.
  • Forecasting: Predict future values. The fable package provides a modern tidy interface for popular models like ETS (Error, Trend, Seasonality) and ARIMA (AutoRegressive Integrated Moving Average).
  • Best Practices: Always visualize your data first. Check for missing values and outliers. Understand the underlying frequency of your data to choose the right model.
  • Resources: The online book Forecasting: Principles and Practice (3rd ed) is the definitive resource for modern time series analysis in R using the tsibble ecosystem.