Skip to main content
v2026.11,986 entries · CC-BY 4.0

Forecast R: Time Series Modeling & Reference

Master forecast in R: fit automated ARIMA and ETS models, evaluate prediction intervals, and run diagnostic tests on research time series.

Written and maintained by CASRAI Editorial Board

Published

On this page

In quantitative scientific research and data analysis, the forecast package in R provides an established, comprehensive framework for displaying, analyzing, and predicting univariate time series data. Developed by Professor Rob J. Hyndman and an international team of contributors, the package automates the complex Box-Jenkins ARIMA parameter estimation and state-space exponential smoothing (ETS) pipelines, allowing researchers to generate robust, reproducible forecasts with calibrated prediction intervals.

What it is used for in research

Time series forecasting is fundamental across empirical research domains, ranging from epidemiological surveillance and climate trend analysis to econometric modeling and laboratory instrumentation monitoring. Researchers use the forecast package to address core analytical challenges:

  • Empirical Econometrics and Financial Analysis: In quantitative economics and policy evaluation, researchers model macroeconomic indicators, inflation rates, and asset volatility. For scholars contrasting empirical methodologies, time series forecasting complements structural estimation approaches covered in our economics vs econometrics comparison.
  • Epidemiology and Public Health: Modeling infectious disease case counts, hospital occupancy rates, and seasonal outbreak trajectories requires algorithms that account for both autoregressive dynamics and seasonal periodicity.
  • Environmental and Climate Sciences: Analyzing cyclical atmospheric carbon measurements, hydrological discharge rates, and temperature anomalies via seasonal decomposition techniques like STL (Seasonal and Trend decomposition using Loess).
  • Experimental Data Monitoring: Researchers tracking laboratory drift, calibration decay, or sensor telemetry alongside classification pipelines such as linear discriminant analysis deploy automated forecasting to identify departures from baseline experimental behaviors.

Install or access (official source only)

The forecast package is officially published and peer-reviewed on the Comprehensive R Archive Network (CRAN). It requires an active installation of R (version ≥ 4.1.0).

Install the current stable release (version 9.0.2, licensed under GPL-3) directly from CRAN using your R console or RStudio environment:

install.packages("forecast", dependencies = TRUE)

Once installed, load the library into your analysis session:

library(forecast)

For researchers testing experimental patches or requiring the development version, the official source code is hosted on GitHub under the maintainer repository (robjhyndman/forecast). It can be installed using the pak package manager or remotes:

# Install development build from GitHub
pak::pak("robjhyndman/forecast")

Step-by-step task

This worked research walkthrough demonstrates how to format time series observations, fit an automated ARIMA model, generate point forecasts with uncertainty intervals, and plot the results in R (answering the practical workflow for forecast in r).

  1. Structure Your Data as a Time Series Object:
    Ensure your raw observations are encapsulated in an R ts object with defined start parameters and sampling frequency (for example, frequency = 12 for monthly data, frequency = 4 for quarterly data, or frequency = 1 for annual series):

    # Example using R built-in monthly atmospheric CO2 measurements
    data("co2")
    class(co2)
    # [1] "ts"
  2. Fit an Automated Model with auto.arima():
    The auto.arima() algorithm conducts automated unit root testing (KPSS test), minimization of the corrected Akaike Information Criterion (AICc), and maximum likelihood estimation across candidate autoregressive and moving average parameters:

    # Fit seasonal ARIMA with exhaustive non-stepwise search for research rigor
    fit_arima <- auto.arima(co2, seasonal = TRUE, stepwise = FALSE, approximation = FALSE)
    summary(fit_arima)
  3. Compute Future Projections with forecast():
    Pass the fitted model object to the generic forecast() function, specifying the forecast horizon h (for example, 24 months) and confidence levels for prediction intervals:

    # Project the next 24 monthly periods at 80% and 95% prediction intervals
    fc <- forecast(fit_arima, h = 24, level = c(80, 95))
    print(fc)
  4. Visualize Forecasts and Historical Trends:
    The package integrates directly with ggplot2 through its S3 autoplot() method. Researchers can visualize baseline projections and inspect regression slopes alongside tools like abline in R:

    library(ggplot2)
    autoplot(fc) +
      labs(
        title = "Atmospheric CO2 Concentration Forecast",
        x = "Observation Year",
        y = "CO2 Concentration (ppm)"
      ) +
      theme_minimal()
  5. Verify Model Residuals:
    Prior to publishing research inferences, evaluate whether the model residuals resemble white noise:

    # Automated residual diagnostic panel and Ljung-Box test
    checkresiduals(fit_arima)

Output and how to read it

The primary result returned by forecast() is an S3 object of class forecast containing numeric matrices of future projections and uncertainty boundaries:

  • Point Forecast: The conditional expectation (mean) of the future probability distribution given historical values and the fitted parameters. In symmetric Gaussian error distributions, this coincides with the conditional median.
  • Lo 80 and Hi 80: The lower and upper bounds of the 80% prediction interval. Under model assumptions, 80% of actual future realizations are expected to fall within this corridor.
  • Lo 95 and Hi 95: The conservative 95% prediction interval bounds, standard in scientific research reporting to reflect parameter uncertainty and future stochastic innovations.

When inspecting model parameters with summary(fit_arima), interpret the key diagnostic metrics:

  • Model Orders (p, d, q) × (P, D, Q)[m]: Indicates non-seasonal autoregressive order p, degree of differencing d, moving average order q, and their seasonal counterparts P, D, Q at seasonal period m.
  • Information Criteria (AIC, AICc, BIC): Used to penalize model complexity. The corrected Akaike Information Criterion (AICc) is the primary metric minimized by auto.arima() to prevent over-fitting in finite sample sizes.
  • Error Measures via accuracy(): Measures in-sample training and out-of-sample testing error: Root Mean Squared Error (RMSE), Mean Absolute Error (MAE), and Mean Absolute Scaled Error (MASE). A MASE value less than 1 indicates the model outperforms a naive one-step baseline.
  • Residual Diagnostics (Ljung-Box Test): The null hypothesis (H₀) states that errors are uncorrelated. A p-value greater than 0.05 indicates the residuals are indistinguishable from white noise. Note that checkresiduals() automatically adjusts the test degrees of freedom by subtracting estimated model parameters (K = p + q + P + Q).

Troubleshooting

Researchers commonly encounter specific operational challenges when running time series analyses in R:

  • Error: y must be a numeric vector or time series: This occurs when passing a data frame or tibble directly into auto.arima() or ets() without isolating the numeric column or indexing the date dimension. Convert your column using ts(data$variable, start = c(YYYY, P), frequency = 12) before model fitting.
  • Residual Autocorrelation Detected (Ljung-Box p-value below 0.05): When default stepwise search settles in a local minimum, significant serial correlation remains in the residuals. Rerun with stepwise = FALSE and approximation = FALSE, or add seasonal Fourier terms or external covariates via the xreg argument.
  • Unit Root Test Inconsistencies: In borderline stationary data, automated KPSS or ADF tests may select excessive differencing (d ≥ 2), leading to over-differenced, highly volatile long-term prediction intervals. Override automated order selection by explicitly setting d = 1 or testing structural breaks.
  • Reproducibility and Script Archiving: Scientific journals increasingly require full computational reproducibility for statistical models. Ensure scripts, package versions, and raw series are published in compliance with our guide on data availability statements for reproducibility.

Free alternatives

While forecast is the historical cornerstone of time series modeling in R, several modern, free, open-source packages serve specialized research workflows:

Tool / Package Ecosystem Primary Modeling Approach Key Strengths in Research Methodological Considerations
forecast R (CRAN) State-space ETS, automated ARIMA, TBATS, STL Long-term stability, automated Box-Jenkins order selection, gold-standard documentation Designed around legacy ts objects; operates on single series sequentially
fable R (Tidyverts) Tidy ETS, ARIMA, dynamic harmonic regression Native integration with tsibble and tidyverse; fits thousands of batch series simultaneously Requires modern tidy data structures; higher architectural overhead for simple single-series tasks
prophet R / Python Generalized Additive Models (GAM) with changepoints Robust to missing data, irregular gaps, and complex holiday effects; intuitive parameters Less suitable for highly autoregressive econometric series without external regressors
stats::arima R (Base) Classical Box-Jenkins ARIMA Pre-installed with base R; zero external dependencies; minimal computational footprint Lacks automated AICc order selection; requires manual identification of differencing and lag structures
statsmodels.tsa Python SARIMAX, Holt-Winters, Vector Autoregression (VAR) Standard Python ecosystem tool; extensive econometric diagnostics and hypothesis testing Manual parameter configuration required; lacks out-of-the-box automated stepwise ARIMA selection

FAQ

How do I generate a forecast in R using auto.arima?

To generate a forecast in R, convert your data into a ts object, fit the model with fit <- auto.arima(data), and call forecast(fit, h = 12) where h is your desired forecast horizon. Visualize the resulting point forecasts and 80% and 95% prediction intervals using autoplot() from the ggplot2 package.

What is the difference between the forecast and fable packages in R?

The forecast package relies on base R ts data structures and processes univariate time series one at a time. The fable package is its modern successor within the Tidyverts framework, designed to work directly on tidy tsibble data objects and capable of fitting, evaluating, and reconciling forecasts across multiple hierarchical time series concurrently.

How does auto.arima select the optimal time series model?

The auto.arima() function applies unit root tests (such as the KPSS test) to determine the necessary degree of differencing (d and D). It then conducts a stepwise or exhaustive search through candidate autoregressive (p, P) and moving average (q, Q) parameters, selecting the model that minimizes the corrected Akaike Information Criterion (AICc) while validating parameter stationarity.

Why do Ljung-Box test degrees of freedom differ for fitted models?

When running a Ljung-Box test on raw observed data, the degrees of freedom equal the number of lags tested. However, when evaluating residuals from a fitted ARIMA(p, d, q) model, the degrees of freedom must be reduced by the number of estimated parameters (p + q + P + Q). The checkresiduals() function in the forecast package handles this adjustment automatically.

Can the forecast package incorporate external predictor variables?

Yes. Both auto.arima() and stlm() support external explanatory variables through the xreg argument. When producing forecasts with forecast(), researchers must provide a matching matrix of future external regressor values covering the entire forecast horizon.

Sources

  • Comprehensive R Archive Network (CRAN). Package ‘forecast’: Forecasting Functions for Time Series and Linear Models (Version 9.0.2, GPL-3). https://cran.r-project.org/web/packages/forecast/index.html
  • Hyndman RJ, Khandakar Y (2008). Automatic time series forecasting: the forecast package for R. Journal of Statistical Software, 27(3), 1–22. https://doi.org/10.18637/jss.v027.i03
  • Hyndman RJ, Athanasopoulos G (2018). Forecasting: Principles and Practice, 2nd edition. OTexts: Melbourne, Australia. https://otexts.com/fpp2/
  • Hyndman RJ, et al. (2026). forecast: Function Reference and Vignettes. https://pkg.robjhyndman.com/forecast/

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Forecast R: Time Series Modeling & Reference

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →