tabts: Comprehensive time-series analysis with publication-ready...

View source: R/tabts.R

tabtsR Documentation

Comprehensive time-series analysis with publication-ready output

Description

tabts() provides a single R4VN-style interface for descriptive time-series analysis, decomposition, stationarity assessment, ACF/PACF, ARIMA/SARIMA/ ARIMAX, ETS, model comparison, validation, forecasting, interrupted time series (ITS), controlled ITS, count ITS, residual diagnostics, flexible graphics, and evidence-linked interpretation.

Usage

tabts(
  outcome,
  time,
  data = NULL,
  model = "auto",
  period = "auto",
  order = NULL,
  seasonal = NULL,
  xreg = NULL,
  group = NULL,
  intervention = NULL,
  population = NULL,
  rate = 1e+05,
  family = c("auto", "gaussian", "poisson", "quasipoisson", "negativebinomial"),
  correlation = c("auto", "none", "ar1", "nw"),
  decompose = c("auto", "stl", "classical", "none"),
  stationarity = TRUE,
  acf = TRUE,
  pacf = TRUE,
  diagnostic = TRUE,
  forecast = 0,
  level = c(0.8, 0.95),
  future_xreg = NULL,
  test = NULL,
  criterion = c("aicc", "rmse", "mae", "mape"),
  missing_time = c("warn", "error", "NA", "zero", "interpolate"),
  duplicate_time = c("error", "mean", "sum", "first"),
  plot = TRUE,
  plots = "auto",
  theme = c("r4vn", "minimal", "classic", "bw"),
  title = NULL,
  subtitle = NULL,
  xlab = NULL,
  ylab = NULL,
  legend = TRUE,
  legend_position = "bottom",
  observed_color = NULL,
  fitted_color = NULL,
  forecast_color = NULL,
  counterfactual_color = NULL,
  intervention_color = NULL,
  linewidth = 0.8,
  point = TRUE,
  point_size = 1.8,
  pi = TRUE,
  pi_alpha = 0.15,
  width = 8,
  height = 5,
  dpi = 300,
  interpret = FALSE,
  language = "en",
  detail = c("full", "brief"),
  show = TRUE,
  console = FALSE,
  digits = 2,
  p_digits = 3,
  model_options = list(),
  diagnostic_options = list(),
  forecast_options = list(),
  its_options = list(),
  table_options = list(),
  interpret_options = list(),
  plot_options = list(),
  ai = FALSE,
  ...
)

Arguments

outcome

Outcome variable. A bare column name or a single character column name. The outcome must be numeric.

time

Time variable. A bare column name or a single character column name. Date, POSIXct, integer/numeric index, and ordered time values are supported. Date-like variables are recommended.

data

Data frame. If NULL, tabts() attempts to use the active R4VN data frame.

model

Analysis engine. One of "auto", "arima", "ets", "compare", "its", or "regression". A vector such as c("arima","ets") is treated as a candidate-model comparison.

period

Seasonal period. Use "auto" to infer common periods from the time variable, or supply a positive integer such as 12 for monthly annual seasonality, 4 for quarterly data, or 52 for weekly data.

order

ARIMA order c(p,d,q). If NULL, forecast::auto.arima() is used when forecast is installed; otherwise tabts() performs a compact AICc-based search with stats::arima() so the default command still works.

seasonal

Seasonal ARIMA order c(P,D,Q). The seasonal period comes from period. Ignored for non-ARIMA engines.

xreg

Optional external regressors. Accepts vars(x1, x2), c("x1", "x2"), or a single bare column name.

group

Optional grouping variable. For ordinary time-series models, separate models are fitted for each group. For ITS, a group variable produces a controlled ITS when its_options$controlled = TRUE (the default when a group is supplied).

intervention

Intervention time(s) for ITS. May be a Date/POSIXct, a value comparable with time, a vector of intervention times, or the name/bare name of a 0/1 intervention indicator column.

population

Optional population/exposure variable for count ITS. When supplied with a count family, log(population) is used as an offset.

rate

Display rate multiplier used for descriptive rate calculations, e.g. 100000. It does not change the count-model offset.

family

ITS family: "auto", "gaussian", "poisson", "quasipoisson", or "negativebinomial".

correlation

ITS residual correlation handling: "auto", "none", "ar1", or "nw". AR(1) via nlme::gls() is available for Gaussian ITS. Newey-West robust covariance requires sandwich.

decompose

Decomposition: "auto", "stl", "classical", or "none". "auto" uses STL when at least two seasonal cycles are present.

stationarity

Logical; run stationarity assessment when possible. ADF and KPSS require tseries; suggested differencing additionally uses forecast when available.

acf, pacf

Logical; calculate ACF/PACF tables and plots.

diagnostic

Logical; calculate residual diagnostics.

forecast

Number of future periods to forecast. Zero disables forecasting. Forecast intervals are prediction intervals for ARIMA/ETS.

level

Forecast interval levels, e.g. c(.80,.95).

future_xreg

Optional data frame/matrix of future xreg values for ARIMAX or time-series regression forecasts. It must contain at least forecast rows and the same xreg variables used for fitting.

test

Optional holdout size for validation. An integer means the number of final observations; a value between 0 and 1 means that proportion of observations.

criterion

Model-selection criterion: "aicc", "rmse", "mae", or "mape". Out-of-sample criteria require test.

missing_time

Handling of missing time points: "warn", "error", "NA", "zero", or "interpolate". Missing time points are never silently converted to zero.

duplicate_time

Handling of duplicate time values within a series: "error", "mean", "sum", or "first".

plot

Logical; create plots. Publication-ready base-R plots are always available; if ggplot2 is installed, tabts() uses ggplot2 automatically.

plots

Character vector selecting plots. "auto" creates the relevant set; "all" is an explicit synonym and "none" suppresses plot creation. Other values include "series", "decomposition", "acf", "pacf", "residual", "forecast", "its", and "counterfactual".

theme

Plot theme: "r4vn", "minimal", "classic", or "bw".

title, subtitle, xlab, ylab

Common plot labels.

legend

Logical; show legends where relevant.

legend_position

Legend position such as "bottom", "top", "left", "right", or "none".

observed_color, fitted_color, forecast_color, counterfactual_color

Optional common layer colors. Leave NULL to use R4VN defaults.

intervention_color

Optional intervention-layer color. Leave NULL to use the R4VN default.

linewidth

Default line width for main series layers.

point

Logical; display observed points on the main series plot.

point_size

Default observed point size.

pi

Logical; display prediction-interval ribbons on forecast plots.

pi_alpha

Prediction-interval ribbon transparency.

width, height, dpi

Default figure width/height in inches and raster resolution used when plot(result, file = ...) saves a figure.

interpret

Logical or one of "brief"/"full". Generate deterministic rule-based interpretation linked to exact numerical evidence from the output. The default is FALSE, keeping the routine report concise; request TRUE, "brief", or "full" when needed.

language

Output language. Currently only "en" is supported; all tables, plots, diagnostics, warnings, and interpretations are produced in English.

detail

Interpretation detail: "full" or "brief".

show

Logical; show a publication-style HTML report. In RStudio the report opens in the Viewer and contains all tables and every generated plot; the primary plot is also sent to the Plots pane. No HTML package is required for this Viewer report.

console

Logical; also print tables to the console.

digits

Number of digits for estimates.

p_digits

Number of digits for p-values.

model_options

Named list of advanced model controls. Important entries include auto_arima, ets, diagnostic_gate, candidate, include_drift, and include_mean. For fixed ARIMA/SARIMA models, tabts() automatically disables a drift term when d + D != 1 and disables a mean term when differencing is present.

diagnostic_options

Named list controlling diagnostics. Important entries include ljung_lag, normality, acf_lag, and alpha.

forecast_options

Named list controlling forecasts. Entries may include bootstrap, biasadj, and history.

its_options

Named list controlling ITS. Entries include controlled, reference_group, time_scale, effect_at, counterfactual, include_season, seasonal_harmonics, nw_lag, and post_min. Seasonal adjustment uses sine/cosine Fourier pairs; seasonal_harmonics controls how many pairs are included. For controlled ITS, the first factor level is the reference unless reference_group is supplied.

table_options

Named list controlling output tables. Entries include ci_level, show_model_selection, show_stationarity, show_diagnostics, and show_interpretation.

interpret_options

Named list controlling interpretation, including alpha, include_assumptions, include_model, include_forecast, include_limitations, and evidence.

plot_options

Deep list controlling plots. This is the main extension point for colors, line types/widths, point shapes/sizes, interval ribbons, axes, date breaks/labels, limits, legends, fonts, grids, reference lines, annotations, intervention/counterfactual layers, facets, and component plots. See Details and examples.

ai

FALSE, TRUE, or a named R4VN AI endpoint. AI is an optional additional layer and is used only when aiask() is available. For a deterministic evidence-linked interpretation, set interpret = TRUE.

...

Reserved for future compatible extensions.

Details

The function is intentionally simple for routine use:

tabts(cases, time = month)

while advanced behavior can be changed through model_options, diagnostic_options, forecast_options, its_options, table_options, interpret_options, and plot_options. This design keeps the public API stable while allowing future extensions.

Core workflow

tabts() follows the R4VN workflow:

  1. validate and regularize the time index;

  2. describe the series;

  3. assess seasonality/stationarity;

  4. fit candidate models;

  5. validate/select the model;

  6. diagnose residuals;

  7. forecast when requested;

  8. produce publication-ready tables and plots;

  9. generate evidence-linked interpretation at the end.

Optional packages and dependency-light defaults

Routine ARIMA/SARIMA, forecasting from fixed/base-selected ARIMA models, regression, decomposition, ACF/PACF, Gaussian ITS, Poisson/quasi-Poisson ITS, Viewer tables, and Viewer figures can run without extra analysis or reporting packages. Optional packages add specialized methods: forecast for Hyndman-Khandakar auto-ARIMA and ETS; tseries for ADF/KPSS; nlme for Gaussian AR(1) ITS; sandwich for Newey-West covariance; MASS for negative-binomial ITS; and ggplot2 for editable ggplot objects.

Flexible plot options

Advanced graphics are changed with nested plot_options. For example:

plot_options = list(
  observed = list(color = "black", linewidth = .8,
                  linetype = "solid", point = TRUE,
                  point_shape = 16, point_size = 2),
  fitted = list(color = "steelblue", linewidth = 1,
                linetype = "dashed"),
  forecast = list(color = "firebrick", linewidth = 1.1),
  pi = list(show = TRUE, alpha = .15, border = FALSE),
  axis = list(
    xlim = NULL, ylim = NULL,
    date_breaks = "6 months", date_labels = "%b %Y",
    y_breaks = NULL, y_log = FALSE
  ),
  legend = list(position = "bottom", title = NULL),
  grid = list(major = TRUE, minor = FALSE),
  intervention = list(line = TRUE, label = TRUE,
                      linetype = "dashed", linewidth = .8),
  counterfactual = list(show = TRUE, linetype = "dotted"),
  reference = list(xline = NULL, yline = NULL),
  facet = list(show = TRUE, ncol = NULL, scales = "fixed"),
  font = list(family = NULL, base_size = 11),
  annotation = NULL
)

When ggplot2 is installed, plots are returned as ordinary ggplot objects and may be edited with standard ggplot2 syntax. Without ggplot2, tabts() returns lightweight r4vn_tabts_plot objects drawn with base R; this keeps the default analysis and Viewer graphics dependency-light.

Interpretation

Every rule-based interpretation row contains a finding, the exact evidence used to create it, a status, and a source. Thus statements about stationarity, model selection, residual adequacy, ITS effects, or forecast uncertainty can always be traced back to a specific result.

Value

An object of class r4vn_tabts. Important components include data, summary, stationarity, decomposition, acf, pacf, model, models, model_info, model_selection, coefficients, diagnostics, validation, forecast, counterfactual, its, interpretation, tables, plots, and metadata. The its component stores the family, correlation structure, intervention timing, and pre/post counts used by ITS. Grouped analyses return class r4vn_tabts_grouped.

Examples


data(dengue_ts)

# 1. Simplest command. Automatic ARIMA works with base R; when forecast is
# installed, ARIMA/ETS comparison becomes available automatically.
m1 <- tabts(cases, time = month, data = dengue_ts)
m1$tables
m1$plots$series

# 2. Forecast six future months with 80% and 95% prediction intervals.
m2 <- tabts(cases, time = month, data = dengue_ts, forecast = 6)
m2$forecast
plot(m2, "forecast")

# 3. Fixed ARIMA using base R only.
m3 <- tabts(cases, time = month, data = dengue_ts,
            model = "arima", order = c(1, 0, 1), forecast = 6)
m3$coefficients
m3$diagnostics

# 4. Seasonal ARIMA/SARIMA.
m4 <- tabts(cases, time = month, data = dengue_ts,
            model = "arima", order = c(1, 1, 1),
            seasonal = c(0, 1, 1), period = 12, forecast = 12)

# 5. ARIMAX with external regressors.
future_weather <- tail(dengue_ts[c("rainfall", "temperature")], 6)
m5 <- tabts(cases, time = month, data = dengue_ts,
            model = "arima", order = c(1, 0, 1),
            xreg = vars(rainfall, temperature), forecast = 6,
            future_xreg = future_weather)

# 6. Time-series regression with trend and seasonal terms; base R only.
m6 <- tabts(cases, time = month, data = dengue_ts,
            model = "regression", forecast = 6)

# 7. Compare ARIMA and ETS when forecast is installed.
if (requireNamespace("forecast", quietly = TRUE)) {
  m7 <- tabts(cases, time = month, data = dengue_ts,
              model = c("arima", "ets"), test = 12,
              criterion = "rmse", forecast = 12)
  m7$model_selection
  m7$validation
}

# 8. Decomposition, ACF and PACF are available in the result.
m8 <- tabts(cases, time = month, data = dengue_ts,
            model = "arima", order = c(1, 0, 1))
m8$decomposition
m8$acf
m8$pacf
plot(m8, "decomposition")
plot(m8, "acf")
plot(m8, "pacf")

# 9. Select only the plots needed in a report.
m9 <- tabts(cases, time = month, data = dengue_ts,
            model = "arima", order = c(1, 0, 1), forecast = 6,
            plots = c("series", "forecast", "residual"))

# 10. Missing time points are never silently converted to zero.
dmiss <- dengue_ts[-20, ]
m10 <- tabts(cases, time = month, data = dmiss,
             missing_time = "interpolate", model = "arima",
             order = c(1, 0, 1), forecast = 6)

# 11. Duplicate time points can be handled explicitly.
ddup <- rbind(dengue_ts, dengue_ts[1, ])
m11 <- tabts(cases, time = month, data = ddup,
             duplicate_time = "mean", model = "arima",
             order = c(1, 0, 1))

# 12. Gaussian interrupted time series using base R.
m12 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "gaussian", correlation = "none")
m12$coefficients
m12$effect_at
plot(m12, "counterfactual")

# 13. Poisson ITS with a population offset; also base R.
m13 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "poisson", population = population,
             rate = 100000, correlation = "none")

# 14. Request effects at clinically meaningful post-intervention times.
m14 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "poisson", population = population,
             correlation = "none",
             its_options = list(effect_at = c(1, 3, 6, 12, 24)))
m14$effect_at

# 15. Intervention may be supplied as a 0/1 indicator column.
dind <- dengue_ts
dind$policy <- as.integer(dind$month >= as.Date("2023-01-01"))
m15 <- tabts(cases, time = month, data = dind, model = "its",
             intervention = policy, family = "poisson",
             population = population, correlation = "none")

# 16. Controlled ITS.
data(dengue_its_control)
m16 <- tabts(cases, time = month, group = group,
             data = dengue_its_control, model = "its",
             intervention = as.Date("2023-01-01"), family = "poisson",
             population = population, correlation = "none",
             its_options = list(reference_group = "Control"))
m16$coefficients
m16$effect_at

# 17. Fit separate ordinary time-series models by group.
m17 <- tabts(cases, time = month, group = group,
             data = dengue_its_control, model = "arima",
             order = c(1, 0, 1), forecast = 3)
names(m17$results)

# 18. Interpretation is OFF by default.
m18 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1))
m18$interpretation

# 19. Turn on evidence-linked interpretation when desired.
m19 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             forecast = 6, interpret = TRUE)
m19$interpretation

# 20. Brief interpretation.
m20 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             interpret = "brief")

# 21. Publication-ready plot customization.
m21 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1), forecast = 12,
             title = "Monthly dengue cases",
             subtitle = "Observed, fitted and forecast values",
             xlab = "Month", ylab = "Cases",
             plot_options = list(
               observed = list(point = TRUE, point_size = 1.6),
               forecast = list(linewidth = 1),
               pi = list(show = TRUE, alpha = .12),
               axis = list(date_breaks = "1 year", date_labels = "%Y"),
               legend = list(position = "bottom")
             ))

# 22. The Viewer report contains every generated table and plot when show=TRUE.
m22 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             forecast = 6, show = TRUE)

# 23. Save a publication figure without another export package.
plot(m22, "forecast",
     file = file.path(tempdir(), "tabts_forecast_300dpi.png"),
     width = 8, height = 5, dpi = 300)

# 24. Use the active R4VN data frame.
usedf(dengue_ts, quiet = TRUE)
m24 <- tabts(cases, time = month, model = "arima",
             order = c(1, 0, 1), forecast = 3)
usedf(clear = TRUE, quiet = TRUE)

# 25. Optional enhancements only when needed:
# tseries -> ADF/KPSS; nlme -> Gaussian AR(1) ITS;
# sandwich -> Newey-West ITS; MASS -> negative-binomial ITS;
# forecast -> auto.arima/ETS; ggplot2 -> editable ggplot objects.

# 26. Explicit ETS when forecast is available.
if (requireNamespace("forecast", quietly = TRUE)) {
  m26 <- tabts(cases, time = month, data = dengue_ts,
               model = "ets", forecast = 6)
  m26$model_info
  m26$forecast
}

# 27. ADF/KPSS stationarity tests are added when tseries is installed.
m27 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             stationarity = TRUE)
m27$stationarity

# 28. Hold out the final 20% of observations for validation.
m28 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1), test = .20)
m28$validation

# 29. Keep tables but suppress plot creation completely.
m29 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             plot = FALSE, show = TRUE)
m29$tables

# 30. Request all relevant figures explicitly.
m30 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             forecast = 6, plots = "all")
names(m30$plots)

# 31. Gaussian ITS: correlation = "auto" uses AR(1) only when nlme is
# available and the correlated model improves AIC sufficiently.
m31 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "gaussian", correlation = "auto")
m31$its

# 32. Newey-West covariance is an optional enhancement via sandwich.
m32 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "poisson", population = population,
             correlation = "nw")
m32$coefficients

# 33. Automatic count-family choice: Poisson, quasi-Poisson, or
# negative-binomial when MASS is available and overdispersion is marked.
m33 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "auto", population = population,
             correlation = "none")
m33$its$family

# 34. Explicit quasi-Poisson ITS requires no additional package.
m34 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "quasipoisson", population = population,
             correlation = "none")
m34$coefficients

# 35. Multiple intervention dates in one segmented model.
m35 <- tabts(cases, time = month, data = dengue_ts,
             model = "its",
             intervention = as.Date(c("2022-01-01", "2023-01-01")),
             family = "poisson", population = population,
             correlation = "none")
m35$coefficients
m35$its

# 36. Add dependency-light Fourier seasonal terms to ITS when required.
m36 <- tabts(cases, time = month, data = dengue_ts,
             model = "its", intervention = as.Date("2023-01-01"),
             family = "poisson", population = population,
             correlation = "none", period = 12,
             its_options = list(include_season = TRUE, seasonal_harmonics = 2))
m36$coefficients

# 37. Customize which tables are shown in the Viewer without deleting the
# underlying result components.
m37 <- tabts(cases, time = month, data = dengue_ts,
             model = "arima", order = c(1, 0, 1),
             table_options = list(show_stationarity = FALSE,
                                  show_validation = FALSE))
names(m37$tables)
m37$stationarity

# 38. If ggplot2 is installed, edit a returned plot as an ordinary ggplot.
if (requireNamespace("ggplot2", quietly = TRUE)) {
  p38 <- m22$plots$forecast + ggplot2::labs(caption = "R4VN tabts")
  print(p38)
}

# 39. Save TIFF or vector PDF directly through plot().
plot(m22, "forecast",
     file = file.path(tempdir(), "tabts_forecast.tiff"),
     width = 8, height = 5, dpi = 300)
plot(m22, "forecast",
     file = file.path(tempdir(), "tabts_forecast.pdf"),
     width = 8, height = 5)

# 40. Inspect reusable components for a custom manuscript/report workflow.
names(m22)
names(m22$tables)
names(m22$plots)
m22$metadata
summary(m22)



R4VN documentation built on Sept. 30, 2026, 5:13 p.m.