ZetCode

R time series

last modified November 19, 2026

A time series is a sequence of observations recorded at regular intervals, and the order of the values carries information that an ordinary vector throws away. R represents such data with the ts class, which stores the values together with a start time and a frequency. The frequency is the number of observations per cycle: twelve for monthly data, four for quarterly data, and one for annual data. This article covers the ts class, windowing and aggregation, seasonal decomposition, autocorrelation, ARIMA models, and forecasts.

Creating a time series

The built-in AirPassengers series records the monthly number of international airline passengers, in thousands, from 1949 to 1960. It is already a ts object with a frequency of twelve. frequency, start, and end read its time metadata, and window selects a slice by time rather than by position.

create-ts.R
passengers <- AirPassengers
cat("class:", class(passengers), "\n")
cat("frequency:", frequency(passengers), "\n")
cat("start:", start(passengers), "\n")
cat("end:", end(passengers), "\n")
print(window(passengers, start = c(1959, 1), end = c(1959, 6)))

The class is ts, the frequency is twelve, and the series runs from January 1949 to December 1960, which is one hundred and forty-four observations. The window for the first six months of 1959 starts at 360 and rises to 472. The printed window keeps the monthly labels, so the output is readable without converting the values back to a plain vector.

$ Rscript create-ts.R
class: ts 
frequency: 12 
start: 1949 1 
end: 1960 12 
     Jan Feb Mar Apr May Jun
1959 360 342 406 396 420 472

Windowing and aggregation

window accepts a start and an end in the same year-and-cycle notation that start reports. Cutting the series at the end of 1954 splits it into an early and a late period. aggregate with FUN = mean collapses each year into one value, which makes the long-term growth easy to see.

ts-window.R
early <- window(AirPassengers, end = c(1954, 12))
late <- window(AirPassengers, start = c(1955, 1))
cat("early mean:", round(mean(early), 1), "\n")
cat("late mean:", round(mean(late), 1), "\n")
cat("growth:", round(mean(late) / mean(early) - 1, 3), "\n")
print(round(aggregate(AirPassengers, FUN = mean), 1))

The early period averages 182.9 thousand passengers and the late period 377.7, a growth of 106.5 percent. The yearly means climb without interruption from 126.7 in 1949 to 476.2 in 1960. The aggregate result is itself a ts object with a frequency of one, which is why its header says Frequency = 1. Windowing by time avoids the off-by-one errors that come from indexing a series by row number.

$ Rscript ts-window.R
early mean: 182.9 
late mean: 377.7 
growth: 1.065 
Time Series:
Start = 1949 
End = 1960 
Frequency = 1 
 [1] 126.7 139.7 170.2 197.0 225.0 238.9 284.0 328.2 368.4 381.0 428.3 476.2

Seasonal decomposition

decompose splits a series into a trend, a seasonal component, and a remainder. The default model is additive, so the three parts sum to the observed value. Applying it to the logarithm of the passenger series turns a multiplicative pattern into an additive one, because a constant percentage growth becomes a constant absolute increase on the log scale.

seasonal.R
parts <- decompose(log(AirPassengers))
cat("trend months:", length(parts$trend), "\n")
print(round(parts$seasonal[1:12], 3))
cat("seasonal range:", round(range(parts$seasonal), 3), "\n")

The trend has 144 entries with missing values at both ends, where a moving average cannot be centred. The seasonal indices are largest in July at 0.211 and smallest in November at -0.216, which on the log scale means roughly twenty-three percent above the trend and nineteen percent below it. The seasonal pattern is stable enough that a single set of twelve indices describes every year.

$ Rscript seasonal.R
trend months: 144 
 [1] -0.086 -0.114  0.018 -0.013 -0.009  0.115  0.211  0.205  0.065 -0.075
[11] -0.216 -0.100
seasonal range: -0.216 0.211 

Autocorrelation

Autocorrelation measures how strongly a series correlates with a shifted copy of itself. acf computes it for lags zero and up, while pacf computes the partial autocorrelation, which removes the effect of the shorter lags. Both functions draw a plot by default; setting plot = FALSE returns the numbers instead.

autocorrelation.R
values <- acf(AirPassengers, lag.max = 6, plot = FALSE)
print(round(as.numeric(values$acf), 3))
partial <- pacf(AirPassengers, lag.max = 6, plot = FALSE)
print(round(as.numeric(partial$acf), 3))

The autocorrelation starts at one, because every series is perfectly correlated with itself at lag zero, and falls only slowly to 0.682 after six months. That slow decay is the signature of a trend: nearby values resemble each other because the level is changing, not because the series oscillates around a fixed mean. The partial autocorrelation is 0.948 at lag one and -0.229 at lag two, so most of the short-range dependence is captured by the first lag. Differencing the series would remove the trend before modelling.

$ Rscript autocorrelation.R
[1] 1.000 0.948 0.876 0.807 0.753 0.714 0.682
[1]  0.948 -0.229  0.038  0.094  0.074  0.008

Fitting an ARIMA model

An ARIMA model describes a series through its own past values and past errors. The notation order = c(p, d, q) gives the number of autoregressive terms, the number of differences, and the number of moving average terms. The script simulates 120 observations from an AR(1) process with a coefficient of 0.7 and then estimates the model as if the coefficient were unknown.

arima-fit.R
set.seed(11)
series <- arima.sim(model = list(ar = 0.7), n = 120)
fit <- arima(series, order = c(1, 0, 0))
print(round(fit$coef, 3))
cat("sigma squared:", round(fit$sigma2, 3), "\n")
cat("log likelihood:", round(fit$loglik, 2), "\n")

The estimated autoregressive coefficient is 0.647 against the true value of 0.7, and the intercept is -0.109. The estimate is close but not exact because 120 observations carry sampling error. The residual variance is 0.918 and the log likelihood is -165.43, two numbers that are used to compare competing models. The seed is fixed at 11, so the simulated series and the estimates are reproducible.

$ Rscript arima-fit.R
      ar1 intercept 
    0.647    -0.109 
sigma squared: 0.918 
log likelihood: -165.43 

Forecasting

A seasonal ARIMA model adds a second set of terms for the cycle. The specification order = c(1, 1, 1) with seasonal = list(order = c(0, 1, 1), period = 12) combines one ordinary difference, one seasonal difference, a nonseasonal AR term, a nonseasonal MA term, and a seasonal MA term at lag twelve. predict returns the future values on the log scale together with their standard errors.

forecast.R
fit <- arima(log(AirPassengers), order = c(1, 1, 1),
             seasonal = list(order = c(0, 1, 1), period = 12))
prediction <- predict(fit, n.ahead = 6)
print(round(exp(prediction$pred), 1))
print(round(exp(prediction$pred + 1.96 * prediction$se), 1))

The model forecasts 450.8 thousand passengers for January 1961, falling to 426.8 in February and then rising through June. The second block applies the exponential function to the prediction plus 1.96 standard errors, which gives an approximate upper bound of the ninety-five percent interval. The interval widens as the horizon grows, from 484.4 in January to 655.3 in June. A forecast is a conditional expectation, not a promise.

$ Rscript forecast.R
       Jan   Feb   Mar   Apr   May   Jun
1961 450.8 426.8 480.6 493.6 510.3 584.9
       Jan   Feb   Mar   Apr   May   Jun
1961 484.4 464.3 527.4 545.8 568.0 655.3

A complete example

The final script combines the pieces. It decomposes the log series to find the strongest and weakest months, fits the same seasonal model on that scale, prints the AIC, and forecasts the first four months of 1961. The AIC penalises the likelihood for the number of parameters, so smaller values are better when models are compared on the same data.

report.R
parts <- decompose(log(AirPassengers))
seasonal <- parts$seasonal[1:12]
fit <- arima(log(AirPassengers), order = c(1, 1, 1),
             seasonal = list(order = c(0, 1, 1), period = 12))
forecast_values <- predict(fit, n.ahead = 12)
cat("strongest month:", month.abb[which.max(seasonal)], "\n")
cat("weakest month:", month.abb[which.min(seasonal)], "\n")
cat("aic:", round(fit$aic, 1), "\n")
print(round(exp(forecast_values$pred[1:4]), 1))

July is the strongest month and November the weakest, which matches the seasonal indices from the decomposition. The AIC is -481.9, a value that only means something next to the AIC of another model fitted to the same series. The four forecasts repeat the January to April values from the previous section, which is expected because both scripts fit the same model. A real analysis would also inspect the residuals of the fit for remaining autocorrelation.

$ Rscript report.R
strongest month: Jul 
weakest month: Nov 
aic: -481.9 
[1] 450.8 426.8 480.6 493.6

Next steps

The dates and times article covers the calendar classes that usually supply the time index of a series, and the descriptive statistics article covers the summaries that describe its level and spread. The probability distributions article explains the normal distribution behind the forecast intervals, and the ANOVA article shows another way of separating signal from noise in grouped data.

Source

R documentation: ts

R documentation: window

R documentation: decompose

R documentation: acf and pacf

R documentation: arima

R documentation: the AirPassengers data set

In this article we have stored monthly data in a ts object and read its frequency and time bounds. We selected periods with window, aggregated them by year, and split a log series into trend and season with decompose. We measured autocorrelation with acf and pacf, fitted an AR(1) model to a simulated series, and used a seasonal ARIMA model to forecast the airline data. The final example combined decomposition, model selection, and forecasting in one script. The series continues with R ggplot2.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.