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

Time Series Analysis in R: Workflow, Modeling, and Diagnostic Methods

A practical researcher guide to time series analysis in R, covering data preparation, structural decomposition, ARIMA modeling, and diagnostic tests.

Written and maintained by CASRAI Editorial Board

Published

On this page

Time series analysis in R is the statistical practice of decomposing, modeling, and forecasting ordered, time-stamped observations using R’s native statistical computing environment and CRAN package ecosystem. Researchers utilize time series workflows to isolate structural components—including underlying secular trends, cyclical seasonality, and stochastic noise—test for stationarity, evaluate lagged autocorrelation structures, and estimate predictive parameterizations such as autoregressive integrated moving average (ARIMA) and state-space systems for empirical investigation and forecasting.

Ask CASRAI · free to tryQuestion about this guide? Ask CASRAI answers with linked sources. 2 free questions a day, no account.

Ask your first question freeSubscribe

What it is used for in research

Time series analysis in R is applied across disciplines where measurements are collected sequentially over regular or irregular temporal intervals. In biomedical and public health surveillance, epidemiologists track disease incidence, vaccination rates, and hospital admission counts over calendar time to detect outbreak signals and evaluate public health policy interventions. In environmental sciences and climatology, researchers analyze continuous sensor telemetry, river discharge volumes, atmospheric greenhouse gas concentrations, and marine temperatures to detect long-term anthropomorphic drifts against cyclical seasonal variation. In economic, financial, and organizational research, analysts model inflation dynamics, research grant expenditure trajectories, and institutional resource utilization to inform budgetary forecasts and risk governance.

Before fitting parametric time series models, empirical researchers routinely evaluate their series through descriptive summaries and temporal exploratory data analysis, establishing baseline distribution parameters using tools like summary in R to inspect central tendency, quartiles, and extreme values. Unlike cross-sectional data, longitudinal time series violate standard ordinary least squares (OLS) assumptions of independent and identically distributed (i.i.d.) observations because sequential values exhibit serial dependence. R provides dedicated classes, specialized estimation routines, and diagnostic tests specifically engineered to model this temporal dependence structure without producing spurious regressions.

Install or access (official source only)

Base R provides fundamental time series infrastructure through the built-in stats package, which ships natively with all official distributions from the Comprehensive R Archive Network (CRAN) and requires no separate package installation. R distributions can be downloaded directly from official CRAN mirror sites maintained under the R Foundation for Statistical Computing.

For specialized unit root testing, automated model identification, and modern tabular time series structures, researchers install curated packages from CRAN within an active R session. The official CRAN Task View for Time Series Analysis, maintained by Rob J. Hyndman and Rebecca Killick, indexes the authoritative ecosystem of peer-reviewed packages. The core packages utilized in standard research workflows include tseries (unit root and stationarity tests), forecast (automated forecasting and residual diagnostics), zoo (regular and irregular indexed series), and tsibble (tidy temporal data frames):

# Install standard time series analysis packages from CRAN
install.packages(c("tseries", "forecast", "zoo", "tsibble"))

# Verify installed versions and active R session configuration
packageVersion("tseries")
packageVersion("forecast")
sessionInfo()

When working with raw tabular datasets containing calendar dates, timestamps, and diverse time zones, researchers routinely pair time series packages with the lubridate package to parse character strings into standardized POSIXct or Date objects before creating formal time series structures.

Core time series data structures in R

R accommodates temporal data across several object classes, each designed for specific analytical workflows, index structures, and mathematical operations. Choosing the appropriate class determines how downstream modeling and visualization functions handle sampling frequencies and calendar dates.

Object Class Package Source Index Mechanism Sampling Regularity Primary Research Use Case
ts stats (Base R) Numeric start, end, and frequency Strictly regular (e.g., monthly, quarterly) Classical Box-Jenkins ARIMA, Holt-Winters, and decomposition routines
zoo zoo (CRAN) Arbitrary ordered index (Date, POSIXct) Regular or irregular Irregular observations, rolling window computations, and missing value interpolation
xts xts (CRAN) POSIXct time-based matrix subclass Regular or irregular High-frequency financial telemetry, multi-asset matrices, and time-bracket subsetting
tsibble tsibble (CRAN) Explicit time index variable plus keys Regular or regularized intervals Tidyverse workflows, multiple grouped panel time series, and fable models

The standard base R class is ts. A base ts object is created using the ts() constructor, which takes a numeric vector or matrix alongside temporal parameters: start (the initial time point, specified as a single number or a vector of c(year, period)), frequency (the number of observations per unit of time), and optional end. For instance, monthly data collected starting in January 2020 uses start = c(2020, 1) and frequency = 12. For quarterly data, frequency = 4 is specified. Base R provides extractor functions start(), end(), frequency(), deltat(), and time() to query the temporal attributes of any ts object.

Step-by-step task: end-to-end time series modeling workflow

Executing an empirical time series investigation in R follows a systematic, seven-step sequence: data structuring, structural decomposition, stationarity testing, dependence diagnostics, parameter estimation, residual diagnostic checking, and out-of-sample projection. The following instructions demonstrate this sequence using standard R syntax.

Step 1: Construct and inspect the time series object

Begin by importing raw temporal data and binding it into an official ts object. In this worked example, we examine monthly counts of research grant applications recorded across a multi-year sampling frame:

# Define monthly observations and construct a regular ts object
obs_values = c(
  112, 118, 132, 129, 121, 135, 148, 148, 136, 119, 104, 118,
  115, 126, 141, 135, 125, 149, 170, 170, 158, 133, 114, 140,
  145, 150, 178, 163, 172, 178, 199, 199, 184, 162, 146, 166,
  171, 180, 193, 181, 183, 218, 230, 242, 209, 191, 172, 194
)

grant_ts = ts(obs_values, start = c(2020, 1), frequency = 12)

# Verify temporal metadata
print(grant_ts)
summary(grant_ts)
start(grant_ts)
end(grant_ts)
frequency(grant_ts)

Step 2: Decompose structural components

Time series typically comprise three unobserved components: a secular trend-cycle component, a seasonal pattern of fixed period, and an irregular remainder (noise). Base R provides two decomposition routines: decompose() for moving-average classical decomposition and stl() for Loess-based seasonal decomposition.

The stl() function, based on Cleveland, Cleveland, McRae, and Terpenning (1990), offers greater statistical flexibility because it accommodates changing seasonal patterns and provides outlier-resistant estimation through its robust = TRUE argument:

# Perform additive Loess decomposition
# s.window = "periodic" enforces a stable seasonal cycle across years
decomp_fit = stl(grant_ts, s.window = "periodic", robust = TRUE)

# Plot the decomposed series (data, seasonal, trend, remainder)
plot(decomp_fit, main = "STL Decomposition of Monthly Grant Applications")

When the magnitude of seasonal oscillations expands proportionally with the rising level of the series, an additive decomposition (Y_t = T_t + S_t + R_t) will exhibit systematic heteroskedasticity in the remainder. In such cases, applying a logarithmic transformation log(grant_ts) stabilizes variance, converting multiplicative relationships into additive ones.

Step 3: Evaluate stationarity with unit root tests

A time series is weakly stationary if its mean, variance, and autocovariances are invariant over time. Stationarity is a fundamental precondition for Box-Jenkins modeling. Researchers should perform a dual testing strategy using both the Augmented Dickey-Fuller (ADF) test and the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test from the tseries package, because they evaluate opposing null hypotheses:

library(tseries)

# Augmented Dickey-Fuller test (H0: unit root present / non-stationary)
adf_res = adf.test(grant_ts, alternative = "stationary")
print(adf_res)

# KPSS test (H0: level or trend stationary / no unit root)
kpss_res = kpss.test(grant_ts, null = "Level")
print(kpss_res)

If adf.test() yields a p-value greater than 0.05 (failing to reject non-stationarity) and kpss.test() yields a p-value less than 0.05 (rejecting stationarity), the series possesses a unit root. First-order differencing is required: diff_ts = diff(grant_ts, differences = 1). If seasonal non-stationarity is also present, seasonal differencing at lag 12 is applied: diff_seasonal = diff(diff_ts, lag = 12).

Step 4: Inspect autocorrelation and partial autocorrelation functions

Once stationarity is achieved through appropriate differencing, researchers analyze empirical correlograms using acf() and pacf() from the base stats package to determine prospective autoregressive (p) and moving average (q) orders. Detailed guidance on interpreting correlograms and diagnosing lag structures is explored in autocorrelation in time-series data.

# Compute and plot autocorrelation and partial autocorrelation functions
par(mfrow = c(1, 2))
acf(diff_ts, lag.max = 36, main = "Sample ACF (Differenced Series)")
pacf(diff_ts, lag.max = 36, main = "Sample PACF (Differenced Series)")
par(mfrow = c(1, 1))

Dashed blue horizontal lines on R’s correlogram plots represent approximate 95% confidence bands calculated at ±1.96 / sqrt(N), where N is the number of observations in the differenced series. Spikes crossing these thresholds denote statistically significant serial correlation at that lag.

Step 5: Estimate model parameters

Model estimation in base R is conducted using stats::arima(). This function fits an ARIMA(p,d,q)(P,D,Q)[s] model via maximum likelihood estimation (MLE) using a Kalman filter state-space representation. For broader theoretical foundations of these parameter specifications, consult ARIMA models for research time series, or explore automated algorithmic selection in forecast in R.

# Fit a seasonal ARIMA(1, 1, 1)(1, 1, 0)[12] model using exact Maximum Likelihood
arima_fit = arima(
  grant_ts,
  order = c(1, 1, 1),
  seasonal = list(order = c(1, 1, 0), period = 12),
  method = "ML"
)

# Display model coefficients, standard errors, and AIC
summary(arima_fit)
print(arima_fit)

Step 6: Diagnostic testing of model residuals

A properly fitted model must reduce the residual series to Gaussian white noise, meaning residuals exhibit zero mean, homoskedastic variance, and no remaining serial correlation. To test for residual independence, researchers execute a Ljung-Box portmanteau test using Box.test().

Crucially, when testing residuals from a fitted ARMA or ARIMA model, the degrees of freedom must be adjusted for the number of estimated AR and MA parameters. In base R, this requires passing the fitdf argument:

# Extract standardized residuals
resids = residuals(arima_fit)

# Run Ljung-Box test with degrees-of-freedom adjustment (fitdf = p + q + P + Q)
# Here p = 1, q = 1, P = 1, Q = 0 -> fitdf = 3
box_test_res = Box.test(resids, lag = 16, type = "Ljung-Box", fitdf = 3)
print(box_test_res)

A p-value greater than 0.05 indicates that the null hypothesis of white noise cannot be rejected, confirming that the model adequately captures the temporal autocorrelation of the series.

Step 7: Generate forecasts and prediction intervals

Once diagnostics confirm model adequacy, projections for future time horizons are computed using the generic predict() method for Arima objects:

# Generate 12-month ahead forecasts with standard errors
fc_pred = predict(arima_fit, n.ahead = 12)

# Calculate 95% prediction intervals (point forecast +/- 1.96 * standard error)
upper_95 = fc_pred$pred + 1.96 * fc_pred$se
lower_95 = fc_pred$pred - 1.96 * fc_pred$se

# Inspect numeric forecast matrix
forecast_table = data.frame(
  Month = time(fc_pred$pred),
  Forecast = as.numeric(fc_pred$pred),
  Lower_95 = as.numeric(lower_95),
  Upper_95 = as.numeric(upper_95)
)
print(head(forecast_table))

Output and how to read it

Interpreting R’s console output requires understanding the specific statistical metrics returned by decomposition and modeling objects.

Reading stl() decomposition output

Calling decomp_fit$time.series returns a multiple time series matrix containing three columns: seasonal, trend, and remainder. Summing these three components across any row reproduces the original value: Y_t = S_t + T_t + R_t. In the plot generated by plot(decomp_fit), each panel features a vertical grey bar on the right margin. These bars represent relative scales: a small grey bar indicates that the component accounts for a large proportion of the series’ total variation, whereas a tall grey bar indicates that the component’s variation is relatively small compared to the overall data range.

Reading arima() model summaries

The console output from print(arima_fit) reports estimated parameters and fit diagnostics:

Call:
arima(x = grant_ts, order = c(1, 1, 1), seasonal = list(order = c(1, 1, 0), period = 12), method = "ML")

Coefficients:
         ar1      ma1     sar1
      0.4120  -0.8142  -0.4891
s.e.  0.1845   0.1128   0.1704

sigma^2 estimated as 48.36:  log likelihood = -118.42,  aic = 244.84

Key output metrics are interpreted as follows:

  • Coefficients and s.e.: The point estimates for autoregressive (ar), moving average (ma), and seasonal (sar, sma) terms. Dividing each coefficient by its standard error (s.e.) produces an approximate z-statistic. A ratio exceeding 1.96 in absolute value indicates statistical significance at the 5% level.
  • sigma^2: The estimated variance of the Gaussian white noise innovations (sigma^2_epsilon). Lower values reflect tighter in-sample tracking.
  • log likelihood: The maximized log-likelihood value under Gaussian errors. Higher (less negative) values indicate superior model fit to the observed data.
  • aic (Akaike Information Criterion): Calculated as -2*ln(L) + 2*k, where k is the number of estimated parameters. AIC penalizes model complexity to mitigate overfitting. When comparing non-nested candidate models fitted to identical data, the model yielding the lowest AIC is preferred.

Troubleshooting

Time series modeling in R involves strict mathematical constraints regarding stationarity, parameter invertibility, and numerical optimization. The following table details common errors encountered during analysis and their methodological solutions.

Error or Warning Message Root Cause Corrective Action
Error in arima(...): non-stationary AR part from CSS Conditional sum-of-squares (CSS) initialization landed outside the stationary invertibility unit circle. Set method = "ML" directly to enforce stationary parameter space bounds during optimization, or increase differencing order d.
Error in stl(...): series is not periodic or has less than two periods The ts object has frequency = 1 or the total length of the series is shorter than twice the seasonal frequency. Verify frequency definition with frequency(x). STL requires at least two full seasonal cycles (e.g., minimum 24 observations for monthly data).
Error in solve.default(...): system is computationally singular Severe multicollinearity among exogenous regressors (xreg) or redundant AR/MA parameterization. Examine correlation matrix of exogenous regressors; remove collinear variables and simplify model orders (e.g., eliminate overlapping AR and MA terms).
Box.test() degrees of freedom mismatch Calling Box.test() without setting fitdf = p + q evaluates residuals against an unadjusted chi-square distribution. Always supply fitdf = length(coefs) when testing ARMA/ARIMA residuals to prevent severely deflated p-values and false claims of adequacy.
Warning in simpleWarning(...): possible convergence problem: optim gave code = 1 The Nelder-Mead or BFGS optimization algorithm reached its iteration limit before gradient convergence. Increase maximum iterations via optim.control = list(maxit = 1000), or provide reasonable starting values via the init parameter.

Free alternatives

While R remains the gold standard for academic econometrics and time series research, several open-source programming ecosystems provide alternative environments for longitudinal modeling.

Platform / Tool Primary Package Ecosystem Core Strengths Trade-Offs for Researchers
Python statsmodels, pmdarima, sktime Seamless integration with deep learning (PyTorch, TensorFlow) and production machine learning pipelines. More fragmented API across statistical modeling; plotting and diagnostic correlograms require more boilerplate code than R.
Julia TimeSeries.jl, StateSpaceModels.jl High-performance computational execution and rapid execution for large-scale simulations and state-space filtering. Smaller community and fewer specialized econometric packages compared to CRAN’s extensive library.
GNU Octave signal, statistics Free MATLAB-compatible environment with matrix-oriented syntax for signal processing and spectral analysis. Limited native support for modern automated ARIMA heuristics, calendar metadata, and tidy data manipulation.
Gretl Built-in Econometric Library Lightweight GUI and scripting language designed specifically for teaching and applied econometric time series. Lacks the broad general-purpose programming capabilities and extensive visualization packages available in R.

Frequently asked questions

How do you define frequency in an R ts object for daily or hourly data?

In base R ts objects, frequency represents the number of observations per repeating seasonal cycle, not the raw calendar interval. For daily data exhibiting a 7-day weekly pattern, set frequency = 7. If modeling an annual 365.25-day cycle with daily observations, set frequency = 365.25. For complex multi-seasonal patterns (such as hourly data exhibiting both a 24-hour daily cycle and a 168-hour weekly cycle), base ts cannot natively represent multiple frequencies simultaneously; researchers should utilize the msts class from the forecast package or modern tsibble structures.

Why do the ADF test and KPSS test sometimes give contradictory stationarity results in R?

The Augmented Dickey-Fuller (ADF) test evaluates the null hypothesis that a unit root is present (non-stationary), whereas the KPSS test evaluates the null hypothesis that the series is stationary around a constant level or trend. When both tests reject their null hypotheses (ADF p-value < 0.05 and KPSS p-value < 0.05), the series is typically trend-stationary or exhibits a structural break rather than pure difference-stationarity. When neither test rejects its null hypothesis, the sample size or statistical power is insufficient to distinguish between a near-unit-root autoregressive process and true stationarity.

Why is fitdf necessary when running Box.test on ARIMA residuals in R?

When portmanteau tests like the Ljung-Box test are computed on raw observed data, the test statistic follows an asymptotic chi-square distribution with degrees of freedom equal to the number of lags (K). However, when applied to the residuals of a fitted ARMA(p, q) model, the estimation of p + q parameters constrains the residuals, shifting the asymptotic distribution. Failing to specify fitdf = p + q causes the test to evaluate the statistic against K degrees of freedom instead of K – (p + q), which deflates the calculated p-value and leads researchers to incorrectly reject valid models.

When should researchers choose base R ts over zoo, xts, or tsibble?

Base R ts is optimal for strictly regular univariate and multivariate series (such as monthly or quarterly macroeconomic indicators) destined for classical econometric routines like stl(), arima(), or HoltWinters(). If the dataset contains irregular timestamps, weekend gaps, missing business days, or intra-day financial transactions, researchers should select zoo or xts. If the research design involves longitudinal panel datasets, grouped multi-entity series, or integration with dplyr and ggplot2 pipelines, tsibble is the superior modern architecture.

How does stats::arima differ from auto.arima in the forecast package?

Base R’s stats::arima() requires the user to specify exact autoregressive, differencing, and moving average orders (p, d, q) manually based on prior theory and correlogram inspection. In contrast, forecast::auto.arima() implements the automated Hyndman-Khandakar algorithm, which conducts unit root tests (KPSS and seasonal unit root tests) to determine differencing orders, followed by a stepwise search minimizing the corrected Akaike Information Criterion (AICc) across candidate parameter orders.

Sources

  • R Core Team. (2026). stats: The R Stats Package — Time-Series Objects (ts). ETH Zurich R Manual. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/ts.html (Accessed 2026-11-15).
  • R Core Team. (2026). stats: ARIMA Modelling of Time Series (arima). ETH Zurich R Manual. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/arima.html (Accessed 2026-11-15).
  • R Core Team. (2026). stats: Seasonal Decomposition of Time Series by Loess (stl). ETH Zurich R Manual. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/stl.html (Accessed 2026-11-15).
  • R Core Team. (2026). stats: Auto- and Cross- Covariance and -Correlation Function Estimation (acf). ETH Zurich R Manual. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/acf.html (Accessed 2026-11-15).
  • R Core Team. (2026). stats: Box-Pierce and Ljung-Box Diagnostic Tests (box.test). ETH Zurich R Manual. https://stat.ethz.ch/R-manual/R-devel/library/stats/html/box.test.html (Accessed 2026-11-15).
  • Hyndman, R. J., and Killick, R. (2026). CRAN Task View: Time Series Analysis. Comprehensive R Archive Network (CRAN). https://cran.r-project.org/web/views/TimeSeries.html (Accessed 2026-11-15).
  • Hyndman, R. J., Athanasopoulos, G., Bergmeir, C., Caceres, G., et al. (2026). forecast: Forecasting Functions for Time Series and Linear Models. CRAN Package Repository. https://cran.r-project.org/web/packages/forecast/index.html (Accessed 2026-11-15).
  • Trapletti, A., and Hornik, K. (2026). tseries: Time Series Analysis and Computational Finance. CRAN Package Repository. https://cran.r-project.org/web/packages/tseries/index.html (Accessed 2026-11-15).

Data: R Time Series Analysis Ecosystem and Function Benchmark

A comparative technical benchmark mapping core time series analysis functions across base R and CRAN packages, indexing computational purposes, input data classes, statistical criteria, and package origins.

R Time Series Analysis Ecosystem and Function Benchmark
Function NamePackageAnalytical PurposeInput Data ClassOptimization or Test Criterion
ts()stats (Base R)Construct regular time series object with frequency attributesnumeric vector or matrixDeterministic temporal indexing
decompose()stats (Base R)Classical moving-average seasonal decompositionts object (frequency > 1)Symmetric moving average smoothing
stl()stats (Base R)Loess seasonal decomposition of time seriests object (frequency > 1)Locally weighted polynomial regression
adf.test()tseries (CRAN)Augmented Dickey-Fuller unit root stationarity testnumeric vector or ts objectt-statistic on lagged level (H0: unit root)
kpss.test()tseries (CRAN)Kwiatkowski-Phillips-Schmidt-Shin stationarity testnumeric vector or ts objectLM test statistic (H0: stationarity)
acf()stats (Base R)Estimate sample autocorrelation and correlogramts object or numeric vectorSample autocovariance normalized by variance
pacf()stats (Base R)Estimate sample partial autocorrelation functionts object or numeric vectorDurbin-Levinson or Yule-Walker recursions
arima()stats (Base R)Fit ARIMA(p,d,q) Box-Jenkins model with Kalman filterts object or numeric vectorMaximum Likelihood / CSS-ML
Box.test()stats (Base R)Portmanteau test for residual autocorrelationnumeric residual vectorLjung-Box Q statistic (fitdf adjusted)
auto.arima()forecast (CRAN)Automated ARIMA order selection algorithmts objectHyndman-Khandakar algorithm minimizing AICc
checkresiduals()forecast (CRAN)Unified residual diagnostic plots and Ljung-Box testfitted model objectPortmanteau test with automated fitdf

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about Time Series Analysis in R: Workflow, Modeling, and Diagnostic Methods

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

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 open 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 →