Package {ggchangepoint}


Type: Package
Title: Combines Changepoint Analysis with 'ggplot2'
Version: 0.4.0
Description: A unified, tidy, 'ggplot2'-native interface to changepoint detection in R. Provides the 'ggcpt' S3 result class with 'broom'-style tidy/glance/augment methods, 'autoplot()' (with confidence intervals, fitted signals, and multivariate facets), composable geoms ('geom_changepoint()', 'geom_cpt_segment()', 'geom_cpt_ci()', 'stat_changepoint()'), and a 'cpt_detect()' dispatcher covering over thirty methods with introspection via 'cpt_methods()': penalised/optimal partitioning (PELT, BinSeg, SegNeigh, AMOC, FPOP, CROPS penalty paths, 'fastcpd', change-in-slope via 'cpop'), multiscale and search methods (WBS, WBS2, NOT, MOSUM, Isolate-Detect, TGUH, SMUCE/HSMUCE with confidence intervals), nonparametric and kernel methods ('changepoint.np', 'ecp', 'kcpRS', 'CptNonPar', sequential 'cpm', self-normalisation via 'SNSeg'), Bayesian methods ('bcp', online 'ocp', 'Rbeast'), high-dimensional and multivariate methods ('InspectChangepoint', 'ocd', 'changepoint.geo'), regression breaks ('strucchange', 'segmented', 'EnvCpt'), and robust detection under drift and autocorrelation ('DeCAFS'). Also includes method comparison, batch/panel detection, bootstrap stability diagnostics, accuracy metrics, Bayesian posterior and run-length plots, interactive rendering, data simulation with canonical test signals, and per-method citations.
License: GPL (≥ 3)
Encoding: UTF-8
Imports: changepoint, changepoint.np, dplyr, ecp, generics, ggplot2 (≥ 3.4.0), lifecycle, Rdpack, stats, tibble, utils
RdMacros: Rdpack
RoxygenNote: 7.3.2
Suggests: rmarkdown, knitr, testthat (≥ 3.0.0), wbs, breakfast, not, mosum, fpop, IDetect, stepR, cpop, bcp, ocp, Rbeast, cpm, kcpRS, CptNonPar, DeCAFS, SNSeg, InspectChangepoint, ocd, changepoint.geo, strucchange, segmented, EnvCpt, fastcpd, plotly, future, future.apply
VignetteBuilder: knitr
URL: https://pursuitofdatascience.github.io/ggchangepoint/
BugReports: https://github.com/PursuitOfDataScience/ggchangepoint/issues
NeedsCompilation: no
Packaged: 2026-08-24 16:18:20 UTC; youzhi
Author: Youzhi Yu [aut, cre]
Maintainer: Youzhi Yu <yuyouzhi666@icloud.com>
Repository: CRAN
Date/Publication: 2026-08-24 18:50:16 UTC

ggchangepoint package

Description

Unified tidy changepoint detection with ggplot2 visualisation.

Details

ggchangepoint provides a consistent S3 result class (ggcpt) for changepoint detection results, broom-style methods (tidy(), glance(), augment()), ggplot2 integration via autoplot() and composable geoms (geom_changepoint(), geom_cpt_segment(), geom_cpt_ci(), stat_changepoint()), and a unified dispatcher cpt_detect() that supports over thirty methods.

**Detection engines.** cpt_detect() currently dispatches to 31 methods across six families (run cpt_methods() for the live table with installation status):

**Key features.** Every detector returns a ggcpt object with a stable tibble(cp, cp_value) contract (plus engine extras such as ci_lower/ci_upper and posterior_prob). Visualise any result directly with autoplot() (confidence intervals, fitted signals, multivariate facets), the Bayesian displays (ggcpt_posterior(), ggcpt_runlength()), or interactively via ggcpt_interactive(). Compare methods with ggcpt_compare(); run panels of series with cpt_batch(); quantify uncertainty with cpt_stability(); sweep penalties with cpt_crops(). Evaluate accuracy with cpt_metrics() and ggcpt_eval(); simulate ground-truth data with cpt_simulate() and the canonical test signals; and cite the methodology behind any result with cpt_cite().

Author(s)

Maintainer: Youzhi Yu yuyouzhi666@icloud.com

See Also

Useful links:


Annotate segments with alternating shading

Description

Adds alternating shaded rectangles to highlight segments between changepoints.

Usage

annotate_segments(cp, n, fill = c("grey90", "white"), alpha = 0.5, ...)

Arguments

cp

Changepoint indices (including 0 and n).

n

Length of the series.

fill

Colors for alternating segments. Defaults to c("grey90", "white").

alpha

Alpha for fill. Defaults to 0.5.

...

Additional arguments passed to annotate.

Value

A list of ggplot annotations.


Augment a ggcpt object

Description

Returns the original data with added columns: seg_id, .fitted, .resid, and is_changepoint.

Usage

## S3 method for class 'ggcpt'
augment(x, ...)

Arguments

x

A ggcpt object.

...

Additional arguments (ignored).

Details

For a multivariate result every coordinate is returned, but the changepoints are shared across them, so seg_id and is_changepoint apply to the whole row while .fitted and .resid describe the first coordinate only — the same coordinate $segments$param_estimate summarises. When an engine supplies its own fitted signal (SMUCE, DeCAFS, cpop, segmented, bcp, beast) that signal is used for .fitted in place of the segment means.

Value

A tibble with the original data plus augment columns.


Autoplot a ggcpt object

Description

Renders a changepoint detection result as a ggplot. The raw series is drawn as a line (with optional points), changepoints are shown as vertical lines, and (optionally) fitted segment levels, the engine's fitted signal, and changepoint-location confidence intervals are overlaid. Multivariate results (from ecp, inspect, geomcp, ...) are drawn as faceted small-multiples with shared changepoint rules.

Usage

## S3 method for class 'ggcpt'
autoplot(
  object,
  show_segments = FALSE,
  show_ci = FALSE,
  show_fit = FALSE,
  cptline_alpha = 1,
  cptline_color = "blue",
  cptline_type = "solid",
  cptline_linewidth = 0.5,
  show_points = NULL,
  show_line = TRUE,
  index = NULL,
  ...
)

Arguments

object

A ggcpt object.

show_segments

Logical. Whether to draw the fitted segment means. Defaults to FALSE.

show_ci

Logical. Whether to draw confidence intervals for changepoint locations, when the engine provides them (columns ci_lower/ci_upper on the changepoints tibble — SMUCE, strucchange, segmented). Drawn as horizontal whiskers near the bottom of the panel. Defaults to FALSE.

show_fit

Logical. Whether to draw the engine's fitted signal (the fitted column of $data, provided by SMUCE, DeCAFS, cpop, segmented, bcp, beast). Defaults to FALSE.

cptline_alpha

Alpha for changepoint lines. Defaults to 1.

cptline_color

Color for changepoint lines. Defaults to "blue".

cptline_type

Linetype for changepoint lines. Defaults to "solid".

cptline_linewidth

Linewidth for changepoint lines. Defaults to 0.5.

show_points

Logical. Whether to draw data points. Auto-off above 500 obs.

show_line

Logical. Whether to draw the line. Defaults to TRUE.

index

Optional vector of x-axis values (e.g. dates) of the same length as the series; defaults to the observation index.

...

Unknown arguments are ignored with a warning.

Value

A ggplot object.


Bayesian changepoint wrapper (Barry-Hartigan product partition model)

Description

Wraps bcp::bcp(), the MCMC implementation (Erdman and Emerson, 2007) of the Barry and Hartigan (1993) product partition model. The engine returns a posterior probability of a changepoint at every location; locations whose posterior probability reaches prob_threshold are reported as changepoints, and the full probability profile is kept so that ggcpt_posterior() can draw the classic two-panel posterior plot.

Usage

bcp_wrapper(x, prob_threshold = 0.5, burnin = 50, mcmc = 500, seed = NULL, ...)

Arguments

x

A numeric vector.

prob_threshold

Posterior probability cutoff in (0, 1) above which a location is reported as a changepoint. Defaults to 0.5.

burnin

Number of burn-in MCMC iterations. Defaults to 50.

mcmc

Number of post-burn-in MCMC iterations. Defaults to 500.

seed

Optional seed for reproducibility of the MCMC run.

...

Additional arguments passed to bcp::bcp().

Value

A ggcpt object. The changepoints tibble carries a posterior_prob column, and the data tibble carries the posterior mean in its fitted column.

References

Barry D, Hartigan JA (1993). “A Bayesian analysis for change point problems.” Journal of the American Statistical Association, 88(421), 309–319.

Erdman C, Emerson JW (2007). “bcp: An R package for performing a Bayesian analysis of change point problems.” Journal of Statistical Software, 23(3), 1–13.

Examples


res <- bcp_wrapper(c(rnorm(60), rnorm(60, 4)), seed = 2026)
res$changepoints
ggcpt_posterior(res)


BEAST wrapper — Bayesian estimation of abrupt change, seasonality, and trend

Description

Wraps Rbeast::beast() (Zhao et al., 2019), a Bayesian model-averaging ensemble that estimates the number and location of trend changepoints together with their posterior occurrence probabilities. Locations whose posterior probability reaches prob_threshold are reported; the probability profile renders via ggcpt_posterior().

Usage

beast_wrapper(x, prob_threshold = 0.5, seed = NULL, ...)

Arguments

x

A numeric vector (treated as a non-seasonal series).

prob_threshold

Posterior probability cutoff in (0, 1) above which a candidate trend changepoint is reported. Defaults to 0.5.

seed

Optional seed for the engine's MCMC sampler (passed to Rbeast::beast() as mcmc.seed).

...

Additional arguments passed to Rbeast::beast().

Value

A ggcpt object. The changepoints tibble carries posterior_prob, and the data tibble carries the posterior mean trend in its fitted column.

References

Zhao K, Wulder MA, Hu T, Bright R, Wu Q, Qin H, Li Y, Toman E, Mallick B, Zhang X, Brown M (2019). “Detecting change-point, trend, and seasonality in satellite time series data to track abrupt changes and nonlinear dynamics: A Bayesian ensemble algorithm.” Remote Sensing of Environment, 232, 111181.

Examples


res <- beast_wrapper(c(rnorm(60), rnorm(60, 4)), seed = 2026)
res$changepoints


Bayesian online changepoint detection wrapper (BOCPD)

Description

Wraps ocp::onlineCPD(), an implementation of Bayesian Online Changepoint Detection (Adams and MacKay, 2007). BOCPD recursively updates a posterior over the current run length (time since the last change); the maximum a posteriori set of changepoints is reported, and the full run-length posterior is kept so that ggcpt_runlength() can draw the signature run-length heatmap.

Usage

bocpd_wrapper(x, hazard = 100, ...)

Arguments

x

A numeric vector.

hazard

Constant hazard rate 1/\lambda of the change process; larger hazard values mean changes are expected less often. Defaults to 100 (the upstream default).

...

Additional arguments passed to ocp::onlineCPD().

Value

A ggcpt object with the MAP changepoint set. The full ocp fit (including the run-length posterior) is kept in $fit.

References

Adams RP, MacKay DJ (2007). “Bayesian online changepoint detection.” arXiv preprint arXiv:0710.3742.

Examples


res <- bocpd_wrapper(c(rnorm(60), rnorm(60, 4)))
res$changepoints
ggcpt_runlength(res)


Sequential change point model wrapper (CPM)

Description

Wraps cpm::processStream() (Ross, 2015) for distribution-free sequential changepoint detection via repeated two-sample tests (Mann-Whitney for location, Mood for scale, Lepage, Kolmogorov-Smirnov and Cramer-von-Mises for general changes, and parametric Student/Bartlett/GLR variants). Although the engine is designed for streams, it is run here over the full series in one pass, mimicking online monitoring with average run length arl0.

Usage

cpm_wrapper(x, cpm_type = "Mann-Whitney", arl0 = 500, startup = 20, ...)

Arguments

x

A numeric vector.

cpm_type

Test statistic, passed to cpm::processStream() as cpmType. Distribution-free: "Mann-Whitney" (location, the default), "Mood" (scale), "Lepage", "Kolmogorov-Smirnov", "Cramer-von-Mises". Parametric: "Student", "Bartlett", "GLR" (Gaussian), "Exponential" (positive data), "FET" (Fisher's exact test, for 0/1 Bernoulli data — this one also needs a lambda value passed through ..., e.g. lambda = 0.3).

arl0

Target in-control average run length (how many observations, on average, before a false alarm). Defaults to 500. cpm ships thresholds only for 100, 200, 370, 400, 500, 600, 700, 1000, 2000, 5000, 10000 and 20000; any other value is refused, because the engine answers it by printing an error and reporting no changepoints.

startup

Number of observations after each restart before monitoring begins. Defaults to 20.

...

Additional arguments passed to cpm::processStream().

Value

A ggcpt object. The changepoints tibble carries a detection_time column: the index at which the sequential test flagged each change (always later than the estimated location).

References

Ross GJ (2015). “Parametric and nonparametric sequential change detection in R: The cpm package.” Journal of Statistical Software, 66(3), 1–20.

Examples


res <- cpm_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints


CPOP wrapper — optimal change-in-slope detection

Description

Wraps cpop::cpop() (Fearnhead, Maidstone and Letchford, 2019; Fearnhead and Grose, 2024): exact penalised estimation of a continuous piecewise-linear mean via dynamic programming with functional pruning. This is the engine behind cpt_detect(change_in = "slope"). The fitted broken line is stored in the fitted column and renders via autoplot(show_fit = TRUE).

Usage

cpop_wrapper(x, penalty = NULL, sd = NULL, ...)

Arguments

x

A numeric vector.

penalty

Penalty for adding a changepoint. Defaults to 2 * log(length(x)). cpt_detect resolves its own "MBIC" default to a stronger numeric value, so the two entry points need not agree unless penalty is given.

sd

Noise standard deviation; when NULL it is estimated from the data by the engine's default difference-based estimator.

...

Additional arguments passed to cpop::cpop().

Value

A ggcpt object with change_in = "slope". For a continuous fit the reported location is the kink point itself.

References

Fearnhead P, Maidstone R, Letchford A (2019). “Detecting changes in slope with an L0 penalty.” Journal of Computational and Graphical Statistics, 28(2), 265–275.

Fearnhead P, Grose D (2024). “cpop: Detecting changes in piecewise-linear signals.” Journal of Statistical Software, 109(7), 1–30.

Examples


set.seed(2026)
y <- cumsum(c(rep(0.3, 100), rep(-0.4, 100))) + rnorm(200)
res <- cpop_wrapper(y)
res$changepoints
ggplot2::autoplot(res, show_fit = TRUE)


Batch changepoint detection over many series

Description

Runs one detector over every series in a collection — the panel-data loop that methodological and applied work both need constantly. Accepts a matrix/data frame (one column per series) or a named list of numeric vectors. Honours future::plan() for parallel execution when the future.apply package is available, with parallel-safe RNG.

Usage

cpt_batch(x, method = "pelt", change_in = "mean", seed = NULL, ...)

## S3 method for class 'ggcpt_batch'
print(x, ...)

## S3 method for class 'ggcpt_batch'
tidy(x, ...)

## S3 method for class 'ggcpt_batch'
autoplot(object, ...)

Arguments

x

For cpt_batch(), a numeric matrix or data frame (columns are series) or a list of numeric vectors; for the print() and tidy() methods, a ggcpt_batch object.

method

Detection method, passed to cpt_detect().

change_in

What to detect change in, passed to cpt_detect().

seed

Optional seed for reproducible parallel execution (passed to future.apply::future_lapply() as future.seed; applied via set.seed() when running sequentially).

...

Additional arguments passed to every cpt_detect() call.

object

A ggcpt_batch object (for autoplot()).

Value

A ggcpt_batch object: a tibble with one row per series and columns series, n_changepoints, changepoints (a list-column of tidy tibbles), and result (a list-column of ggcpt objects). Methods: print(), tidy() (one row per changepoint across all series), and autoplot() (faceted small-multiples with each series' changepoints).

Examples

set.seed(2026)
X <- cbind(a = c(rnorm(60), rnorm(60, 4)), b = rnorm(120))
batch <- cpt_batch(X, method = "pelt")
batch
tidy(batch)
ggplot2::autoplot(batch)

Cite the method behind a result

Description

Returns the bibliographic reference(s) for the method behind a ggcpt result (or a method name), so an analysis can cite the right methodological paper without leaving R.

Usage

cpt_cite(x)

Arguments

x

A ggcpt object, a method name (e.g. "pelt"), or missing — in which case references for every known method are returned.

Value

A tibble with columns method and reference, invisibly; the references are also printed.

Examples

cpt_cite("pelt")
res <- cpt_detect(c(rnorm(50), rnorm(50, 5)), method = "pelt")
cpt_cite(res)

CROPS — the full penalty path of a penalised changepoint method

Description

Runs PELT once per distinct optimal segmentation as the penalty ranges over [pen_min, pen_max], using the CROPS algorithm of Haynes, Eckley and Fearnhead (2017) as implemented by the changepoint package. Instead of committing to one penalty, the analyst sees every segmentation the data admits along the path, together with its cost, and picks the elbow.

Usage

cpt_crops(
  x,
  change_in = c("mean", "var", "meanvar"),
  pen_min = NULL,
  pen_max = NULL,
  ...
)

## S3 method for class 'ggcpt_path'
autoplot(
  object,
  type = c("elbow", "path", "segmentations"),
  max_facets = 12,
  ...
)

## S3 method for class 'ggcpt_path'
print(x, ...)

## S3 method for class 'ggcpt_path'
tidy(x, ...)

Arguments

x

For cpt_crops(), a numeric vector; for the print() and tidy() methods, a ggcpt_path object.

change_in

What to detect change in: "mean", "var", or "meanvar". Defaults to "mean".

pen_min, pen_max

The penalty interval to sweep. Default to log(n) and 10 * log(n).

...

Additional arguments passed to the underlying changepoint::cpt.mean(), cpt.var(), or cpt.meanvar() call.

object

A ggcpt_path object (for autoplot()).

type

Plot type for autoplot(): "elbow" (cost against number of changepoints, the classic CROPS diagnostic), "path" (number of changepoints against penalty), or "segmentations" (the data faceted by solution, with that solution's changepoints drawn).

max_facets

Maximum number of solutions shown by type = "segmentations". Defaults to 12.

Value

A ggcpt_path object: a list with a solutions tibble (one row per distinct segmentation: penalty, n_cpts, cost, and a cpts list-column), the data, and metadata. Methods: print(), tidy(), and autoplot() (elbow plot by default; type = "path" for penalty vs. number of changepoints; type = "segmentations" for the faceted segmentations).

References

Haynes K, Eckley IA, Fearnhead P (2017). “Computationally efficient changepoint detection for a range of penalties.” Journal of Computational and Graphical Statistics, 26(1), 134–143.

Killick R, Eckley I (2014). “changepoint: An R package for changepoint analysis.” Journal of statistical software, 58(3), 1–19.

Examples

set.seed(2026)
x <- c(rnorm(100), rnorm(100, 3), rnorm(100, -1))
path <- cpt_crops(x)
path
ggplot2::autoplot(path)
ggplot2::autoplot(path, type = "segmentations")

Unified changepoint detection dispatcher

Description

Runs a changepoint detection method on a sequence and returns a tidy ggcpt result object. This is the recommended entry point for most users. See cpt_methods() for the full method table with engines and capabilities.

Usage

cpt_detect(x, method = "pelt", change_in = "mean", penalty = "MBIC", ...)

Arguments

x

A numeric vector for univariate methods, or a numeric matrix/data frame (rows are time points) for the multivariate methods ("ecp", "inspect", "geomcp", "ocd", "npmojo", "kcp", "fastcpd").

method

Detection method. One of "pelt", "binseg", "segneigh", "amoc", "np", "ecp", "fpop", "wbs", "wbs2", "not", "mosum", "idetect", "tguh", "smuce", "hsmuce", "cpop", "bcp", "bocpd", "beast", "cpm", "kcp", "npmojo", "decafs", "sn", "inspect", "ocd", "geomcp", "strucchange", "segmented", "envcpt", or "fastcpd". Methods whose engines live in Suggests prompt for installation when missing.

change_in

What to detect change in. One of "mean", "var", "meanvar", "slope", or "distribution". Defaults to "mean". The requested value is validated against the method's capabilities (see cpt_methods()); incompatible combinations error rather than silently running something else.

penalty

Penalty type or value. Either a character string ("MBIC", "BIC", "SIC", "AIC", "Hannan-Quinn", "None") or a numeric penalty value. Defaults to "MBIC". See the penalty-semantics section of cpt_penalty for how each engine interprets it; methods that use thresholds, significance levels, or posteriors instead of penalties ignore this argument, and "segneigh" falls back to "SIC" because changepoint does not implement MBIC for Segment Neighbourhood. Note also that the default "MBIC" is resolved to a numeric value for the numeric-penalty engines ("fpop", "cpop", "decafs"), and that value is stronger than those wrappers' own 2 * log(n) default — 19.9 against 11.8 at n = 360 — so cpt_detect(x, method = "decafs") can report fewer changepoints than decafs_wrapper(x) on the same series. Pass penalty explicitly to make the two entry points agree.

...

Additional arguments passed to the specific wrapper (see the wrapper's help page for engine-specific options). Where an argument is also derived from change_in (not's contrast, cpm's cpm_type, kcp's running_stat, sn's parameter, fastcpd's family), a value supplied here takes precedence. Check the spelling against the wrapper's help page: several engines end their own signature in ... (wbs, not, Rbeast, strucchange, segmented, fastcpd), so for those a misspelt argument name is silently discarded upstream and the engine quietly uses its default rather than reporting the typo.

Value

A ggcpt object.

Scale sensitivity of the penalised change-in-mean engines

"pelt", "binseg", "segneigh" and "fpop" compare a penalty against a raw segment cost when change_in = "mean": changepoint's Normal cost assumes a noise standard deviation of 1, and fpop's lambda is an absolute penalty on the residual sum of squares. Neither rescales the data, so on a series whose noise is much wider than 1 the penalty is effectively negligible and the segmentation shatters. On one true changepoint with a jump of five standard deviations, "pelt" returns 1 changepoint at \sigma = 1, 29 at \sigma = 3 and 138 at \sigma = 10. Three ways to avoid it, in order of convenience:

The other engines are unaffected: SMUCE, WBS, WBS2, NOT, MOSUM, Isolate-Detect, TGUH, CPOP, DeCAFS and the Bayesian, nonparametric and multivariate methods all estimate or cancel the noise scale internally, and return the same segmentation whatever the units.

Examples

set.seed(2022)
x <- c(rnorm(100, 0, 1), rnorm(100, 10, 1))
result <- cpt_detect(x, method = "pelt", change_in = "mean")
result
ggplot2::autoplot(result)

Introspect available changepoint detection methods

Description

Returns a tibble describing every method the package knows about — those that are wired and those that are planned — along with their capabilities and installation status. Useful for discovering what can be run and what needs to be installed.

Usage

cpt_methods()

Value

A tibble with columns:

method

Method name as passed to cpt_detect().

change_in

What types of change the method can detect.

engine

The upstream R package that implements the method.

status

"available" (wired in this release) or "planned" (future).

installed

TRUE if the engine package is installed, FALSE if it is a Suggests engine that is missing, NA for planned methods.

target_release

What a planned method is waiting on: a release, or "when on CRAN" when the engine package itself is not available from CRAN. NA for methods that are already wired. Asking cpt_detect() for a planned method reports this rather than claiming the name does not exist.

Examples

cpt_methods()

Changepoint accuracy metrics

Description

Computes standard accuracy metrics comparing predicted changepoints to ground truth, including precision/recall/F1 with margin, covering metric, Hausdorff distance, adjusted Rand index, annotation error, and MAE/RMSE of matched locations.

Usage

cpt_metrics(pred, truth, n, margin = 5)

Arguments

pred

Predicted changepoint indices (integer vector).

truth

Ground truth changepoint indices (integer vector).

n

Length of the series.

margin

Tolerance margin for matching (default 5).

Details

Precision/recall use a one-to-one matching: each truth may be claimed by at most one prediction (predictions are scanned in order and take the earliest unmatched truth within margin, which yields a maximum matching for interval-structured problems). When pred and truth are both empty the segmentation is exactly right, so precision, recall, and F1 are all 1. The covering metric follows van den Burg and Williams (2020): the prediction-side partition is always well defined, so an empty pred scores the covering of the trivial single-segment partition rather than 0.

Value

A tibble with columns: n, n_pred, n_truth, precision, recall, f1, covering, hausdorff, rand_index, annotation_error, mae_matched, rmse_matched.

Examples

cpt_metrics(c(100, 200), c(100, 200), n = 300)
cpt_metrics(c(101, 205), c(100, 200), n = 300, margin = 5)

Multi-annotator evaluation

Description

Computes averaged covering and F1 scores against multiple annotation sets, as used in the Turing Change Point Dataset benchmark.

Usage

cpt_metrics_annotated(pred, annotations, n, margin = 5)

Arguments

pred

Predicted changepoint indices.

annotations

A list of ground-truth annotation vectors.

n

Length of the series.

margin

Tolerance margin (default 5).

Value

A tibble with averaged metrics.


Construct changepoint penalties

Description

Helper to construct standard penalty values for use with changepoint detection methods. Returns a numeric penalty value.

Usage

cpt_penalty(type, n = NULL, k = 1, value = NULL, alpha = 1.01)

Arguments

type

Penalty type: "None", "BIC" (or "SIC"), "MBIC", "AIC", "Hannan-Quinn", "sSIC", or "Manual".

n

Series length (at least 3 for the \log n-based penalties). Required for BIC, MBIC, AIC, Hannan-Quinn, sSIC.

k

Number of parameters per changepoint (typically 2 for mean+variance, 1 for mean-only). Defaults to 1. The "MBIC" penalty additionally reads k as the number of changepoints being placed, in its \log{n \choose k} term.

value

Numeric value for Manual type.

alpha

Exponent of the strengthened SIC ("sSIC") penalty k (\log n)^\alpha; must exceed 1. Defaults to 1.01 (Fryzlewicz, 2014).

Value

A numeric penalty value.

Penalty semantics across engines

The same penalty name may be interpreted differently by different engines:

Examples

cpt_penalty("BIC", n = 100)
cpt_penalty("AIC", n = 100)
cpt_penalty("Manual", value = 5)

Generate simulated changepoint data

Description

Creates a synthetic time series with known changepoints for testing and benchmarking.

Usage

cpt_simulate(
  n,
  changepoints = integer(),
  change_in = c("mean", "var", "meanvar", "slope"),
  params = NULL,
  noise = c("gauss", "t", "ar1", "rw"),
  sd = 1,
  df = 3,
  rho = 0,
  seed = NULL
)

rcpt(...)

Arguments

n

Length of the series.

changepoints

Integer vector of changepoint locations (last index of each segment before the change).

change_in

What changes: "mean", "var", "meanvar", or "slope".

params

A list of parameters per segment. For mean changes, a vector of segment means. For var changes, a vector of segment sds. For meanvar, a list of lists with mean and sd per segment. For slope, a list with intercept and slope per segment. When NULL, every segment gets the same neutral parameters, so the series has no actual change. Supplying fewer entries than there are segments recycles the last one and warns, because the trailing changepoints would then be recorded as ground truth without a change behind them.

noise

Noise type: "gauss" (Gaussian), "t" (Student-t), "ar1" (AR(1)), or "rw" (random walk).

sd

Noise standard deviation, non-negative (for Gaussian and t; t-noise is rescaled so its standard deviation is exactly sd). Defaults to 1.

df

Degrees of freedom for t-noise; must exceed 2 so the variance exists. Defaults to 3.

rho

AR(1) autocorrelation parameter, strictly between -1 and 1 for stationarity. Defaults to 0. Used only when noise = "ar1".

seed

Optional seed for reproducibility.

...

Passed to cpt_simulate.

Value

A tibble with columns index, value, and seg_id. The true changepoints are stored in the true_changepoints attribute.

Examples

dat <- cpt_simulate(200, changepoints = c(100), change_in = "mean",
                    params = c(0, 10), seed = 2022)
attr(dat, "true_changepoints")

Changepoint stability diagnostics via bootstrap

Description

Most engines report a point set of changepoints with no measure of how fragile it is. cpt_stability() fits the detector once, then resamples residuals within the fitted segments (so the estimated regime structure is preserved), re-runs the detector on each replicate, and reports how often each location is re-detected. The resulting detection-frequency profile is a cheap, model-agnostic confidence signal available for every wrapped engine, including the many that ship no confidence intervals.

Usage

cpt_stability(x, method = "pelt", B = 100, margin = 5, seed = NULL, ...)

## S3 method for class 'ggcpt_stability'
print(x, ...)

## S3 method for class 'ggcpt_stability'
autoplot(object, ...)

Arguments

x

For cpt_stability(), a numeric vector; for the print() method, a ggcpt_stability object.

method

Detection method, passed to cpt_detect().

B

Number of bootstrap replicates. Defaults to 100.

margin

Tolerance (in indices) when counting a replicate detection as a re-detection of a location. Defaults to 5.

seed

Optional seed for reproducibility.

...

Additional arguments passed to every cpt_detect() call.

object

A ggcpt_stability object (for autoplot()).

Value

A ggcpt_stability object: a list with frequency (a tibble of index and freq, the proportion of replicates detecting a changepoint within margin of that index), original (the point-estimate ggcpt), and B. Methods: print() and autoplot() (frequency profile with the original detections marked).

Examples

set.seed(2026)
x <- c(rnorm(60), rnorm(60, 4))
st <- cpt_stability(x, method = "pelt", B = 20)
st
ggplot2::autoplot(st)

Changepoint wrapper

Description

This function wraps a number of cpt functions from the changepoint package and the cpt.np() function from the changepoint.np package. It is handy that users can use this function to get the same changepoint results as these functions output individually. Moreover, it returns a tibble that inherits the tidyverse style. Functions from the changepoint package do require data normality assumption by default, yet changepoint.np is a non-parametric way to detect changepoints and let data speak by itself. If user sets change_in as np (or cpt_np), a seed should be set before using the function for the sake of reproducibility. For more details on the changepoint and changepoint.np packages, please refer to their documentation.

Usage

cpt_wrapper(data, change_in = "mean_var", cp_method = "PELT", ...)

Arguments

data

A numeric vector.

change_in

Choice of mean_var, mean, var, and np (or cpt_np for backward compatibility). Each choice corresponds to cpt.meanvar(), cpt.mean(), cpt.var() and cpt.np() respectively. The default is mean_var.

cp_method

A wide range of choices (i.e., AMOC, PELT, SegNeigh or BinSeg). Please note when change_in is np or cpt_np, PELT is the only option.

...

Extra arguments for each cpt function mentioned in the change_in section.

Value

A tibble including which point(s) is/are the changepoint along with raw changepoint value corresponding to that changepoint. Changepoint locations follow the convention of the changepoint package: the last index of the left segment. The upstream cpt object is attached as the "ggcpt_fit" attribute, which is what cpt_detect() stores in the result's $fit.

Standardise the data for a change in mean

With change_in = "mean" the upstream Normal cost assumes a noise standard deviation of 1 and the penalty is compared against the raw residual sum of squares, so a series with wider noise is under-penalised and over-segmented: 29 changepoints instead of 1 at \sigma = 3 in a measured example. Standardise the series first, or use change_in = "mean_var", which estimates a variance per segment and is unaffected. See the scale-sensitivity section of cpt_detect.

References

Killick R, Eckley I (2014). “changepoint: An R package for changepoint analysis.” Journal of statistical software, 58(3), 1–19.

Examples

set.seed(2022)
cpt_wrapper(c(rnorm(100,0,1),rnorm(100,0,10)))
cpt_wrapper(c(rnorm(100,0,1),rnorm(100,10,1)))


DeCAFS wrapper — changes amid drift and autocorrelated noise

Description

Wraps DeCAFS::DeCAFS() (Romano, Rigaill, Runge and Fearnhead, 2022), which detects abrupt mean changes when the underlying signal also drifts (random-walk fluctuations) and the noise is AR(1)-autocorrelated — the two regimes in which plain change-in-mean methods over-detect. Model parameters are estimated automatically unless supplied.

Usage

decafs_wrapper(x, penalty = NULL, model_param = NULL, ...)

Arguments

x

A numeric vector.

penalty

Penalty \beta for adding a changepoint. Defaults to 2 * log(length(x)). cpt_detect resolves its own "MBIC" default to a stronger numeric value — on a five-changepoint series that is 3 changepoints through the dispatcher against 5 here — so pass penalty explicitly when the two must agree.

model_param

Optional list of model parameters (sdEta, sdNu, phi) as accepted by DeCAFS::DeCAFS(); when NULL they are estimated from the data.

...

Additional arguments passed to DeCAFS::DeCAFS().

Value

A ggcpt object. The data tibble carries the estimated signal in its fitted column.

References

Romano G, Rigaill G, Runge V, Fearnhead P (2022). “Detecting abrupt changes in the presence of local fluctuations and autocorrelated noise.” Journal of the American Statistical Association, 117(540), 2147–2162.

Examples


set.seed(2026)
res <- decafs_wrapper(c(rnorm(100), rnorm(100, 5)))
res$changepoints


ecp wrapper

Description

The ecp package provides a non-parametric way to detect changepoints. Unlike the changepoint package, it does not assume raw data to have any formal distribution. This wrapper function wraps two functions from the ecp package, i.e., e.divisive() and e.agglo(). Users can use either function by switching the algorithm argument. Before using the wrapper function, seed should be set for the sake of reproducibility.

Usage

ecp_wrapper(data, algorithm = "divisive", min_size = 2, seed = NULL, ...)

Arguments

data

A numeric vector (for univariate) or matrix/data.frame (for multivariate).

algorithm

Either divisive or agglo. divisive is the default.

min_size

Minimum number of observations between change points. By default is 2. This argument is only applied when algorithm = "divisive".

seed

Optional. A seed for reproducibility of the stochastic permutation test.

...

Extra arguments to pass on either from e.divisive() or e.agglo().

Value

A tibble includes which point(s) is/are the changepoint along with raw changepoint value corresponding to that changepoint. Changepoint locations follow the ecp package convention: the first index of the right segment. When no changepoint is found, an empty tibble is returned (0 rows). The upstream fit is not retained — and $fit is NULL on a ggcpt from cpt_detect(method = "ecp") — because ecp::e.agglo()'s cluster-progression matrix is quadratic in the series length; call the ecp functions directly if you need their full output.

References

James NA, Matteson DS (2014). “ecp: An R package for nonparametric multiple change point analysis of multivariate data.” Journal of Statistical Software, 62(7), 1–25. doi:10.18637/jss.v062.i07.

Examples

set.seed(2022)
ecp_wrapper(c(rnorm(100,0,1),rnorm(100,0,10)))
ecp_wrapper(c(rnorm(100,0,1),rnorm(100,10,1)))


EnvCpt wrapper — changepoints versus trends versus autocorrelation

Description

Wraps EnvCpt::envcpt() (Beaulieu and Killick, 2018), which fits up to twelve competing models — constant mean or linear trend, each with or without changepoints, and with white-noise, AR(1) or AR(2) errors — and lets an information criterion decide whether the series really contains changepoints or merely trend/autocorrelation ("memory"). The changepoints of the winning model (if any) are returned, and the winning model's name is recorded, guarding against the classic false positive of running a mean-shift detector on autocorrelated data.

Usage

envcpt_wrapper(
  x,
  models = c("mean", "meancpt", "meanar1", "meanar2", "meanar1cpt", "meanar2cpt",
    "trend", "trendcpt", "trendar1", "trendar2", "trendar1cpt", "trendar2cpt"),
  criterion = c("AIC", "BIC"),
  minseglen = 5,
  ...
)

Arguments

x

A numeric vector.

models

Character vector of models to fit; see EnvCpt::envcpt(). Defaults to all twelve.

criterion

Model selection criterion: "AIC" (default) or "BIC".

minseglen

Minimum segment length. Defaults to 5.

...

Additional arguments passed to EnvCpt::envcpt().

Value

A ggcpt object. $fit holds the full envcpt output; the selected model name is stored in the penalty descriptor and printed by glance() via penalty_type. Individual model fits that fail are expected — the criterion ignores them — so the engine's own try() output is not passed on; genuine warnings still are, and a series on which no model fits at all raises an error.

References

Beaulieu C, Killick R (2018). “Distinguishing trends and shifts from memory in climate data.” Journal of Climate, 31(23), 9519–9543.

Examples


set.seed(2026)
res <- envcpt_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints


fastcpd wrapper — fast changepoint detection via sequential gradient descent

Description

Wraps the fastcpd package (Li and Zhang, 2024), a modern PELT-family engine that pairs pruning with sequential gradient descent so that exact or near-exact segmentations of many model families run in near-linear time. This wrapper exposes the time-series families most useful alongside the other engines: mean, variance, mean-and-variance, and AR/ARMA/GARCH model changepoints.

Usage

fastcpd_wrapper(
  x,
  family = c("mean", "variance", "meanvariance", "ar", "arma", "garch"),
  order = NULL,
  ...
)

Arguments

x

A numeric vector, or (for family "mean", "variance", "meanvariance") a matrix with one row per time point for multivariate detection.

family

Model family: "mean", "variance", "meanvariance", "ar", "arma", or "garch". Defaults to "mean".

order

Model order for "ar" (a single integer), "arma" (length-2), or "garch" (length-2). Defaults to 1 for AR, c(1, 1) otherwise.

...

Additional arguments passed to the corresponding fastcpd::fastcpd.*() function (e.g. beta, trim).

Value

A ggcpt object.

References

Li X, Zhang X (2024). “fastcpd: Fast change point detection in R.” arXiv preprint arXiv:2404.05933.

Examples


set.seed(2026)
res <- fastcpd_wrapper(c(rnorm(100), rnorm(100, 4)))
res$changepoints


FPOP wrapper — Functional Pruning Optimal Partitioning

Description

Wraps the fpop package for optimal changepoint detection via functional pruning.

Usage

fpop_wrapper(x, penalty = NULL, ...)

Arguments

x

A numeric vector.

penalty

Penalty value. Defaults to 2 * log(length(x)) (BIC). This is an absolute penalty on the residual sum of squares, so it is only calibrated for noise of standard deviation 1: on wider data the default under-penalises badly and the segmentation shatters. Standardise the series, or scale the penalty by the noise variance (for example 2 * log(length(x)) * stats::var(diff(x)) / 2). See the scale-sensitivity section of cpt_detect. This default differs from the one cpt_detect applies, which resolves its "MBIC" default to a stronger numeric value, so the two entry points need not agree unless penalty is given.

...

Additional arguments passed to fpop::Fpop().

Value

A ggcpt object.


Changepoint vertical rules geom

Description

Draws vertical lines at changepoint locations. Mimics geom_vline but designed to work with the tidy changepoint data frames returned by the package. Can be used as a standalone layer: geom_changepoint(data = cp_df, aes(xintercept = cp)).

Usage

geom_changepoint(
  mapping = NULL,
  data = NULL,
  ...,
  na.rm = FALSE,
  show.legend = NA
)

Arguments

mapping

Set of aesthetic mappings created by ggplot2::aes(). Requires xintercept.

data

A data frame with changepoint information.

...

Other arguments passed to geom_vline.

na.rm

If FALSE, missing values are removed.

show.legend

Whether to show legend.

Value

A ggplot layer.


Changepoint confidence interval geom

Description

Draws horizontal whiskers for changepoint-location confidence intervals (e.g. from MOSUM, stepR, strucchange, segmented).

Usage

geom_cpt_ci(mapping = NULL, data = NULL, ..., na.rm = FALSE, show.legend = NA)

Arguments

mapping

Aesthetic mappings. Requires y (the height at which to draw the whisker) together with xmin and xmax. An x aesthetic is accepted but not needed: the layer is a horizontal error bar, so the interval is given by xmin/xmax and the changepoint itself is usually marked with a separate point layer, as autoplot(show_ci = TRUE) does.

data

A data frame with CI information.

...

Other arguments passed to geom_errorbarh.

na.rm

If FALSE, missing values are removed.

show.legend

Whether to show legend.

Value

A ggplot layer.


Changepoint segment level geom

Description

Draws horizontal segments representing the estimated level of each segment between changepoints. Typically used with data from augment().

Usage

geom_cpt_segment(
  mapping = NULL,
  data = NULL,
  ...,
  na.rm = FALSE,
  show.legend = NA
)

Arguments

mapping

Aesthetic mappings. Requires x, xend, y, yend.

data

A data frame with segment information.

...

Other arguments passed to geom_segment.

na.rm

If FALSE, missing values are removed.

show.legend

Whether to show legend.

Value

A ggplot layer.


Geometrically-inspired multivariate changepoint wrapper (geomcp)

Description

Wraps changepoint.geo::geomcp() (Grundy, Killick and Mihaylov, 2020): each multivariate observation is mapped to its distance from, and angle to, a reference point, and univariate PELT is run on the two mapped series. Distance changes capture shifts in magnitude, angle changes capture shifts in orientation/correlation structure.

Usage

geomcp_wrapper(
  x,
  penalty = "MBIC",
  mapping = c("both", "distance", "angle"),
  ...
)

Arguments

x

A numeric matrix or data frame with one row per time point.

penalty

Penalty for the univariate PELT runs (a changepoint-style character penalty). Defaults to "MBIC".

mapping

Which mapped series' changepoints to report: "both" (union, default), "distance", or "angle".

...

Additional arguments passed to changepoint.geo::geomcp().

Value

A ggcpt object whose changepoints tibble carries a mapping column ("distance" or "angle"; a location found in both is labelled "both").

References

Grundy T, Killick R, Mihaylov G (2020). “High-dimensional changepoint detection via a geometrically inspired mapping.” Statistics and Computing, 30, 1155–1166.

Examples


set.seed(2026)
X <- rbind(matrix(rnorm(100 * 4), 100), matrix(rnorm(100 * 4, 2), 100))
res <- geomcp_wrapper(X)
res$changepoints


Compare multiple changepoint detection methods

Description

Runs several detectors on the same data and returns a faceted or overlaid ggplot comparison. Respects future::plan() for parallel execution if the future.apply package is available.

Usage

ggcpt_compare(
  x,
  methods = c("pelt", "binseg", "amoc"),
  layout = c("facet", "overlay"),
  change_in = "mean",
  seed = NULL,
  ...
)

Arguments

x

A numeric vector (the data series). A one-column matrix or data frame is accepted; wider input is refused, because these detectors are univariate and flattening the columns would invent a changepoint at every seam. Use cpt_batch() for a panel of series.

methods

Character vector of method names (passed to cpt_detect).

layout

Layout type. "facet" (default) shows one panel per method; "overlay" draws all changepoints in one panel, colour-coded.

change_in

What to detect change in. Passed to each detector.

seed

Optional seed for reproducible parallelism. Passed to future.apply::future_lapply() as future.seed, and to set.seed() when running sequentially. Left NULL under a parallel plan, future.seed = TRUE is used, so the workers get parallel-safe streams but the run is not reproducible.

...

Additional arguments passed to each detector.

Value

A ggplot object.

Examples

set.seed(2022)
x <- c(rnorm(100, 0, 1), rnorm(100, 10, 1))
ggcpt_compare(x, methods = c("pelt", "binseg"))

Comparison table

Description

Returns a tidy tibble combining the results of multiple detectors on the same series.

Usage

ggcpt_compare_table(
  x,
  methods = c("pelt", "binseg", "amoc"),
  change_in = "mean",
  ...
)

Arguments

x

A numeric vector (the data series). A one-column matrix or data frame is accepted; wider input is refused, because these detectors are univariate and flattening the columns would invent a changepoint at every seam. Use cpt_batch() for a panel of series.

methods

Character vector of method names.

change_in

What to detect change in.

...

Additional arguments passed to each detector.

Value

A tibble with columns method, cp, cp_value.


Evaluation visualization

Description

Overlays predictions and ground truth on the series with tolerance windows, colouring true positives, false positives, and misses. Uses the same one-to-one matching as cpt_metrics(), so the plot and the metrics agree.

Usage

ggcpt_eval(pred, truth, data_vec, margin = 5)

Arguments

pred

Predicted changepoint indices.

truth

Ground truth changepoint indices.

data_vec

The original data vector (for context).

margin

Tolerance margin (default 5).

Value

A ggplot object.


Interactive changepoint plot

Description

Renders a ggcpt result (or any ggplot built from one) as an interactive HTML widget via plotly, with values on hover. A thin convenience wrapper: the static autoplot() path is untouched.

Usage

ggcpt_interactive(x, ...)

Arguments

x

A ggcpt object or a ggplot object.

...

Additional arguments passed to autoplot() when x is a ggcpt object.

Value

A plotly htmlwidget.

Examples


res <- cpt_detect(c(rnorm(50), rnorm(50, 5)), method = "pelt")
ggcpt_interactive(res)


Coerce, format, and plot ggcpt objects

Description

Convenience S3 methods for working with ggcpt objects: coerce the changepoints to a tibble or data frame, render a one-line summary string, or produce the default plot (a base-graphics fallback that delegates to autoplot.ggcpt).

Usage

## S3 method for class 'ggcpt'
as_tibble(x, ..., .name_repair = NULL)

## S3 method for class 'ggcpt'
as.data.frame(x, row.names = NULL, optional = FALSE, ...)

## S3 method for class 'ggcpt'
format(x, ...)

## S3 method for class 'ggcpt'
plot(x, ...)

Arguments

x

A ggcpt object.

...

Additional arguments passed to methods.

.name_repair

Ignored (the changepoints tibble already has valid, unique names); present for signature compatibility with the generic.

row.names, optional

Passed to as.data.frame.

Value

as_tibble() and as.data.frame() return the changepoints table; format() returns a length-one character string; plot() returns a ggplot object.

Examples

set.seed(2022)
res <- cpt_detect(c(rnorm(50), rnorm(50, 5)), method = "pelt")
as_tibble(res)
as.data.frame(res)
format(res)

Posterior probability plot for Bayesian results

Description

Draws the classic Bayesian changepoint display: the series with its posterior mean (top panel) and the per-location posterior probability of a changepoint (bottom panel). Works with results from bcp_wrapper() and beast_wrapper().

Usage

ggcpt_posterior(x, prob_threshold = NULL)

Arguments

x

A ggcpt object produced by a Bayesian wrapper.

prob_threshold

Probability cutoff drawn as a horizontal reference line in the probability panel; defaults to the threshold recorded on the object (or 0.5).

Value

A ggplot object (two facets sharing the x axis).

Examples


res <- bcp_wrapper(c(rnorm(60), rnorm(60, 4)), seed = 2026)
ggcpt_posterior(res)


Run-length posterior heatmap for Bayesian online results

Description

Draws the signature BOCPD graphic: the posterior distribution of the run length (time since the last changepoint) at every observation, as a heatmap, with the series overlaid on top. Works with results from bocpd_wrapper().

Usage

ggcpt_runlength(x, prob_floor = 0.001)

Arguments

x

A ggcpt object produced by bocpd_wrapper().

prob_floor

Posterior probabilities below this value are not drawn (keeps the heatmap legible). Defaults to 1e-3.

Value

A ggplot object.

Examples


res <- bocpd_wrapper(c(rnorm(60), rnorm(60, 4)))
ggcpt_runlength(res)


Plot for the changepoint package

Description

The plot for changepoints detected by the changepoint package is a line plot for the raw data and the vertical lines representing each changepoint. The x-axis is the row number of the raw data in the original data vector. The plot inherits ggplot2, meaning users can add ggplot2 functions on top the changepoint plot for customization.

Usage

ggcptplot(
  data,
  change_in = "mean_var",
  cp_method = "PELT",
  ...,
  cptline_alpha = 1,
  cptline_color = "blue",
  cptline_type = "solid",
  cptline_linewidth = 0.5,
  cptline_size = lifecycle::deprecated(),
  index = NULL,
  show_points = NULL,
  show_line = TRUE
)

Arguments

data

A numeric vector.

change_in

Choice of mean_var, mean, var, and np (or cpt_np for backward compatibility). Each choice corresponds to cpt.meanvar(), cpt.mean(), cpt.var() and cpt.np() respectively. The default is mean_var.

cp_method

A wide range of choices (i.e., AMOC, PELT, SegNeigh or BinSeg). Please note when change_in is np or cpt_np, PELT is the only option.

...

Extra arguments for each cpt function mentioned in the change_in section.

cptline_alpha

The value of alpha for the vertical changepoint line(s), default is 1, meaning no transparency.

cptline_color

The color for the vertical changepoint line(s), default is blue.

cptline_type

The linetype for the vertical changepoint line(s), default is solid.

cptline_linewidth

The linewidth for the vertical changepoint line(s), default is 0.5.

cptline_size

Deprecated. Use cptline_linewidth instead.

index

Optional. A vector of x-axis labels (e.g. dates) of the same length as data.

show_points

Logical. Whether to draw data points. Defaults to TRUE when length(data) <= 500, FALSE otherwise.

show_line

Logical. Whether to draw the line. Defaults to TRUE.

Value

A line plot with data points along with the vertical lines representing changepoints.

Examples

ggcptplot(c(rnorm(100,0,1),rnorm(100,0,10)))
ggcptplot(c(rnorm(100,0,1),rnorm(100,10,1)))


Plot for the ecp package

Description

The plot for changepoints detected by the ecp package is a line plot for the raw data and the vertical lines representing each changepoint. The x-axis is the row number of the raw data in the original data vector. The plot inherits ggplot2, meaning users can add ggplot2 functions on top the changepoint plot for customization.

Usage

ggecpplot(
  data,
  algorithm = "divisive",
  min_size = 2,
  ...,
  cptline_alpha = 1,
  cptline_color = "blue",
  cptline_type = "solid",
  cptline_linewidth = 0.5,
  cptline_size = lifecycle::deprecated(),
  index = NULL,
  show_points = NULL,
  show_line = TRUE
)

Arguments

data

A numeric vector (for univariate) or matrix/data.frame (for multivariate).

algorithm

Either divisive or agglo. divisive is the default.

min_size

Minimum number of observations between change points. By default is 2. This argument is only applied when algorithm = "divisive".

...

Extra arguments to pass on either from e.divisive() or e.agglo().

cptline_alpha

The value of alpha for the vertical changepoint line(s), default is 1, meaning no transparency.

cptline_color

The color for the vertical changepoint line(s), default is blue.

cptline_type

The linetype for the vertical changepoint line(s), default is solid.

cptline_linewidth

The linewidth for the vertical changepoint line(s), default is 0.5.

cptline_size

Deprecated. Use cptline_linewidth instead.

index

Optional. A vector of x-axis labels (e.g. dates) of the same length as data.

show_points

Logical. Whether to draw data points. Defaults to TRUE when length(data) <= 500, FALSE otherwise.

show_line

Logical. Whether to draw the line. Defaults to TRUE.

Value

A line plot with data points along with the vertical lines representing changepoints.

Examples

ggecpplot(c(rnorm(100,0,1),rnorm(100,0,10)))
ggecpplot(c(rnorm(100,0,1),rnorm(100,10,1)))


Glance at a ggcpt object

Description

Returns a one-row summary of a changepoint detection result.

Usage

## S3 method for class 'ggcpt'
glance(x, ...)

Arguments

x

A ggcpt object.

...

Additional arguments (ignored).

Details

total_cost is reported on whatever scale the engine itself uses, so it is meaningful when comparing penalties within one method and not when comparing one method against another. For the changepoint engines it is the unpenalised -2\log L of the chosen segmentation. Four cases there are NA rather than filled with a number that would not mean the same thing:

Value

A one-row tibble with columns: n, n_changepoints, method, change_in, penalty_type, penalty_value, cp_convention, total_cost (NA when the engine does not expose a cost), runtime (elapsed seconds when measured by cpt_detect(), otherwise NA).


Isolate-Detect wrapper

Description

Wraps the IDetect package. Requires the IDetect package.

Usage

idetect_wrapper(x, seed = NULL, ...)

Arguments

x

A numeric vector.

seed

Optional seed for reproducibility.

...

Additional arguments passed to IDetect::ID().

Value

A ggcpt object. When the engine finds no changepoints (including when it signals "No change-points found"), an empty result is returned rather than an error. A constant series likewise returns the empty result; see the note below.

Constant input

IDetect::ID() does not treat a flat series consistently — its statistics become 0/0, and what comes back depends on the value and the length. rep(3, 200) yields 126 changepoints, at 1, 3, 4, 6, 7, ...; rep(0, 100) raises "No change-points found"; rep(-2.5, 60) returns the sentinel 0. A constant series plainly has no changepoint, and every other search wrapper here reports none, so this one short-circuits to the empty result. Constancy is decided by exact equality, so a series with tiny but genuine variation still reaches the engine.


inspect wrapper — high-dimensional changepoints via sparse projection

Description

Wraps InspectChangepoint::inspect() (Wang and Samworth, 2018). For a p-variate series whose mean changes in an unknown sparse subset of coordinates, the algorithm computes the CUSUM transformation, finds the optimal sparse projection direction via a convex relaxation, and locates changepoints on the projected univariate series, recursing via wild binary segmentation.

Usage

inspect_wrapper(x, lambda = NULL, threshold = NULL, ...)

Arguments

x

A numeric matrix or data frame with one row per time point and one column per coordinate.

lambda

Regularisation parameter of the sparse projection; when NULL the engine default \sqrt{\log(p \log n)/2} is used.

threshold

Detection threshold; when NULL it is computed by Monte Carlo (via the engine).

...

Additional arguments passed to InspectChangepoint::inspect().

Value

A ggcpt object. The changepoints tibble carries a strength column (the maximum projected CUSUM statistic). The first coordinate is used for cp_value and the univariate plot line; the full matrix is kept for the faceted multivariate autoplot(). Coordinates that are constant carry no changepoint information and would make the engine's variance rescaling undefined, so they are dropped (with a warning) before detection and an all-constant matrix returns an empty result; the dropped coordinates are still kept for plotting, and reported locations always refer to the original rows.

References

Wang T, Samworth RJ (2018). “High dimensional change point estimation via sparse projection.” Journal of the Royal Statistical Society: Series B, 80(1), 57–83.

Examples


set.seed(2026)
X <- cbind(c(rnorm(80), rnorm(80, 3)), c(rnorm(80), rnorm(80, -2)),
           rnorm(160))
res <- inspect_wrapper(X)
res$changepoints


Test if an object is a ggcpt object

Description

Test if an object is a ggcpt object

Usage

is_ggcpt(x)

Arguments

x

An object to test.

Value

TRUE if x inherits from ggcpt.


Kernel changepoint wrapper (KCP on running statistics)

Description

Wraps kcpRS::kcpRS() (Cabrieto et al., 2018; the KCP framework of Arlot, Celisse and Harchaoui, 2019). The data are mapped to a running statistic (mean, variance, autocorrelation, or correlation) computed on a sliding window, and a Gaussian-kernel change point analysis with a permutation significance test is run on the statistic. Detecting changes in running correlations or variances captures higher-order changes that mean-based methods miss. Multivariate input (matrix or data frame) is supported.

Usage

kcp_wrapper(
  x,
  running_stat = c("mean", "var", "autocorr", "corr"),
  wsize = 25,
  nperm = 1000,
  kmax = 10,
  alpha = 0.05,
  seed = NULL,
  ...
)

Arguments

x

A numeric vector, matrix, or data frame (columns are variables).

running_stat

Which running statistic to monitor: "mean", "var", "autocorr", or "corr" (correlation requires at least two columns). Defaults to "mean".

wsize

Sliding window size for the running statistic. Defaults to 25.

nperm

Number of permutations for the significance test, at least 2. Defaults to 1000. Fewer than two leaves the engine with no permutation distribution: it reports no changepoints at all for 0, and fails inside its own code for 1.

kmax

Maximum number of changepoints considered. Defaults to 10.

alpha

Significance level of the permutation test. Defaults to 0.05.

seed

Optional seed for reproducibility of the permutation test.

...

Additional arguments passed to kcpRS::kcpRS().

Value

A ggcpt object. Reported locations refer to the centre of the sliding window in which the change occurs. The series must be at least wsize long to form one window. Constant coordinates make every running statistic NA, so they are dropped (with a warning) before detection and an all-constant input returns an empty result.

References

Arlot S, Celisse A, Harchaoui Z (2019). “A kernel multiple change-point algorithm via model selection.” Journal of Machine Learning Research, 20(162), 1–56.

Cabrieto J, Adolf J, Tuerlinckx F, Kuppens P, Ceulemans E (2018). “Detecting long-lived autodependency changes in a multivariate system via change point detection and regime switching models.” Scientific Reports, 8, 15637.

Examples


res <- kcp_wrapper(c(rnorm(60), rnorm(60, 3)), nperm = 100, seed = 2026)
res$changepoints


MOSUM wrapper — Moving Sum

Description

Wraps the mosum package for moving-sum-based changepoint detection, either at a single bandwidth or (with multiscale = TRUE) across a bandwidth grid with localised pruning.

Usage

mosum_wrapper(x, G = NULL, multiscale = FALSE, seed = NULL, ...)

Arguments

x

A numeric vector.

G

Bandwidth. If NULL, automatically selected (min(n/10, 100), but never below 2, for the single-bandwidth procedure; the engine's default bandwidth grid for the multiscale procedure). A bandwidth of 1 leaves the engine's local variance estimate undefined, so the automatic choice is floored at 2.

multiscale

Logical. Use the multiscale MOSUM procedure (mosum::multiscale.localPrune()) instead of a single bandwidth? Defaults to FALSE.

seed

Optional seed for reproducibility.

...

Additional arguments passed to mosum::mosum() or mosum::multiscale.localPrune().

Value

A ggcpt object.


Create a ggcpt object

Description

Create a ggcpt object

Usage

new_ggcpt(
  changepoints = tibble::tibble(cp = integer(), cp_value = numeric()),
  segments = tibble::tibble(seg_id = integer(), start = integer(), end = integer(), n =
    integer(), param_estimate = numeric()),
  data = tibble::tibble(index = integer(), value = numeric()),
  method = NA_character_,
  change_in = NA_character_,
  penalty = list(type = NA_character_, value = NA_real_),
  fit = NULL,
  call = NULL,
  cp_convention = "left",
  runtime = NA_real_
)

Arguments

changepoints

A tibble with columns cp and cp_value.

segments

A tibble with segment information: seg_id, start, end, n, param_estimate.

data

A tibble with index and value.

method

Character. The detection method used. A length-one string; defaults to NA_character_. (A zero-length value would make glance() return zero rows instead of its documented single row, because every other column would be recycled against it.)

change_in

Character. What was detected (e.g. "mean", "var", "meanvar"). A length-one string; defaults to NA_character_.

penalty

A list with type and value.

fit

The raw upstream object. Every wrapper stores one except "ecp": ecp::e.agglo() returns a cluster-progression matrix that is quadratic in the series length, so keeping it by default would make the result object explode on a long series. Call ecp::e.divisive() or ecp::e.agglo() directly if you need it.

call

The matched call.

cp_convention

Character. The convention for reporting changepoint locations: "left" (last index of left segment, used by changepoint) or "right" (first index of right segment, used by ecp). Defaults to "left".

runtime

Numeric. Elapsed detection time in seconds, if measured. Defaults to NA.

Value

An object of class ggcpt.


NOT wrapper — Narrowest-Over-Threshold

Description

Wraps the not package for changepoint detection via the Narrowest-Over-Threshold method. The contrast determines what change is detected: piecewise-constant mean (default), mean and variance, or (continuous or discontinuous) piecewise-linear trend.

Usage

not_wrapper(x, contrast = "pcwsConstMean", seed = NULL, ...)

Arguments

x

A numeric vector.

contrast

Contrast type. One of "pcwsConstMean", "pcwsLinContMean", "pcwsLinMean", "pcwsConstMeanVar". Defaults to "pcwsConstMean".

seed

Optional seed for reproducibility.

...

Additional arguments passed to not::not().

Value

A ggcpt object whose change_in reflects the contrast: "mean", "meanvar", or "slope".


Nonparametric MOSUM wrapper (NP-MOJO)

Description

Wraps CptNonPar::np.mojo() (McGonigle and Cho, 2025): nonparametric moving-sum detection of changes in the marginal or joint distribution of a (possibly multivariate) time series, robust to serial dependence.

Usage

npmojo_wrapper(x, G = NULL, lag = 0, ...)

Arguments

x

A numeric vector or matrix (rows are time points).

G

Moving-window bandwidth. Defaults to max(20, 0.1 * n) observations, capped at n / 2 — the largest bandwidth the engine accepts — so the default also works on series shorter than 40.

lag

Time lag at which changes in the joint distribution are examined; 0 targets the marginal distribution. Defaults to 0.

...

Additional arguments passed to CptNonPar::np.mojo().

Value

A ggcpt object. Constant coordinates leave the kernel statistics undefined, so they are dropped (with a warning) before detection and an all-constant input returns an empty result. The engine calibrates its detection threshold by bootstrap, so the value recorded in the penalty descriptor varies between runs; call set.seed() beforehand, or pass threshold = "manual" and threshold.val through ..., for a reproducible one.

References

McGonigle ET, Cho H (2025). “Nonparametric data segmentation in multivariate time series via joint characteristic functions.” Biometrika, 112(2), asaf024.

Examples


res <- npmojo_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints


ocd wrapper — online high-dimensional changepoint detection

Description

Wraps the ocd package (Chen, Wang and Samworth, 2022): online multiscale detection of a mean change in a high-dimensional stream, with worst-case detection-delay guarantees and per-observation cost independent of history. The detector assumes standardised data with known pre-change mean; this wrapper estimates the baseline mean and standard deviation from an initial training window, then monitors the remainder of the series, resetting after each declaration so multiple changes can be found.

Usage

ocd_wrapper(
  x,
  train = NULL,
  thresh = "MC",
  patience = 5000,
  beta = 1,
  mc_reps = 100,
  ...
)

Arguments

x

A numeric matrix or data frame with one row per time point and at least two columns. The ocd detector is inherently high-dimensional and cannot be constructed for a single coordinate, so univariate input is rejected; use a univariate engine (see cpt_methods()) for one series.

train

Number of initial observations used to estimate the baseline mean/sd (not monitored). Defaults to max(20, floor(0.2 * n)), capped at n/2.

thresh

Threshold specification passed to ocd::ChangepointDetector(); "MC" (default) calibrates by Monte Carlo, which is what makes this the slowest wrapper — see the timing note below. Supplying the three thresholds directly, as a named numeric vector c(diag =, off_d =, off_s =), skips calibration altogether.

patience

Target average run length to false alarm. Defaults to 5000.

beta

Assumed lower bound on the squared Euclidean norm of the mean change. Defaults to 1.

mc_reps

Monte Carlo repetitions for threshold calibration. Defaults to 100. The cost is linear in this and grows with the number of coordinates; see the timing note below.

...

Additional arguments passed to ocd::ChangepointDetector().

Value

A ggcpt object. Because the detector is online, reported locations are declaration times (the changepoint plus the detection delay), stored together with a declared_at column.

How long this takes

Nearly all of the run time is ocd's Monte Carlo threshold calibration, which happens before a single observation is read. It is linear in mc_reps and grows with the number of coordinates: measured at mc_reps = 5, construction takes about 3 s at p = 3, 9 s at p = 10 and 55 s at p = 50, and four times as long at mc_reps = 20. At the default mc_reps = 100 that extrapolates to roughly a minute at p = 3 and a quarter of an hour at p = 50. Monitoring the observations afterwards is cheap by comparison — well under a second for a thousand of them. Lower mc_reps while exploring, or pass thresh directly to skip calibration entirely.

References

Chen Y, Wang T, Samworth RJ (2022). “High-dimensional, multiscale online changepoint detection.” Journal of the Royal Statistical Society: Series B, 84(1), 234–266.

Examples



set.seed(2026)
X <- rbind(matrix(rnorm(60 * 3), 60), matrix(rnorm(40 * 3, 3), 40))
res <- ocd_wrapper(X, mc_reps = 5)
res$changepoints



Print a ggcpt object

Description

Print a ggcpt object

Usage

## S3 method for class 'ggcpt'
print(x, ...)

Arguments

x

A ggcpt object.

...

Additional arguments (ignored).


Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

generics

augment, glance, tidy

ggplot2

autoplot

tibble

as_tibble


Broken-line regression wrapper (segmented)

Description

Wraps segmented::segmented() (Muggeo, 2003, 2008): maximum likelihood estimation of continuous piecewise-linear ("broken-line") regressions, with standard errors and confidence intervals for the breakpoint locations. Where the step-change engines model jumps in the level, segmented models kinks in the trend, so change_in is "slope" and the fitted broken line is stored in the fitted column for autoplot(show_fit = TRUE).

Usage

segmented_wrapper(x, npsi = 1, conf_level = 0.95, seed = NULL, ...)

Arguments

x

A numeric vector; a linear model of x on time 1:length(x) is segmented.

npsi

Number of breakpoints to estimate. Defaults to 1.

conf_level

Confidence level for breakpoint intervals. Defaults to 0.95.

seed

Optional seed (the estimator uses bootstrap restarting).

...

Additional arguments passed to segmented::segmented().

Value

A ggcpt object with ci_lower/ci_upper columns and the fitted broken line in $data$fitted. Breakpoints are rounded to the nearest index; for a continuous fit the reported location is the kink itself. A constant series has no kink and returns an empty result, rather than the arbitrary breakpoint a singular fit would give.

References

Muggeo VM (2003). “Estimating regression models with unknown break-points.” Statistics in Medicine, 22(19), 3055–3071.

Muggeo VM (2008). “segmented: An R package to fit regression models with broken-line relationships.” R News, 8(1), 20–25.

Examples


set.seed(2026)
y <- cumsum(c(rep(0.5, 100), rep(-0.3, 100))) + rnorm(200)
res <- segmented_wrapper(y, npsi = 1)
res$changepoints
ggplot2::autoplot(res, show_fit = TRUE, show_ci = TRUE)


Blocks test signal

Description

The classic Donoho-Johnstone blocks test signal with known changepoints.

Usage

signal_blocks(n = 2048, seed = NULL)

Arguments

n

Length of the signal. Defaults to 2048.

seed

Optional seed.

Value

A tibble with columns index and value. The true_changepoints attribute contains the known changepoint locations.

References

Donoho, D. L. and Johnstone, I. M. (1994). Ideal spatial adaptation by wavelet shrinkage. Biometrika, 81(3), 425-455.


FMS (Four-Metric-Segments) test signal

Description

A piecewise-constant test signal from the WBS/NOT literature.

Usage

signal_fms(n = 2000, seed = NULL)

Arguments

n

Length of the signal. Defaults to 2000.

seed

Optional seed.

Value

A tibble with columns index and value.


Mix test signal

Description

A piecewise-constant/linear signal from the literature.

Usage

signal_mix(n = 2000, seed = NULL)

Arguments

n

Length of the signal. Defaults to 2000.

seed

Optional seed.

Value

A tibble with columns index and value.


Stairs test signal

Description

A monotonically stepping signal (staircase).

Usage

signal_stairs(n = 2000, seed = NULL)

Arguments

n

Length of the signal. Defaults to 2000.

seed

Optional seed.

Value

A tibble with columns index and value.


Teeth test signal

Description

A piecewise-constant signal with regularly spaced changepoints.

Usage

signal_teeth(n = 2000, seed = NULL)

Arguments

n

Length of the signal. Defaults to 2000.

seed

Optional seed.

Value

A tibble with columns index and value.


SMUCE / HSMUCE wrapper — multiscale changepoint inference

Description

Wraps stepR::stepFit() for the Simultaneous MUltiscale Changepoint Estimator (SMUCE) of Frick, Munk and Sieling (2014) and its heterogeneous extension HSMUCE (Pein, Sieling and Munk, 2017). SMUCE estimates a step function subject to a simultaneous multiscale test at level alpha; the level bounds the probability of over-estimating the number of changepoints, and the fit delivers confidence intervals for every changepoint location, which populate the ci_lower/ci_upper columns of the result and render via autoplot(show_ci = TRUE) or geom_cpt_ci().

Usage

smuce_wrapper(x, alpha = 0.5, family = c("gauss", "hsmuce"), ...)

Arguments

x

A numeric vector.

alpha

Significance level of the multiscale test in (0, 1); smaller values yield more conservative (fewer-changepoint) fits. Defaults to 0.5, the upstream recommendation for estimation.

family

Noise model: "gauss" (SMUCE, homogeneous Gaussian noise) or "hsmuce" (HSMUCE, segment-wise variance). Defaults to "gauss". The remaining stepR families ("jsmurf", "mDependentPS", ...) all require a filter or covariance specification; call stepR::stepFit() directly for those. "hsmuce" additionally refuses a series whose point-to-point variation lies more than about seven orders of magnitude below its own scale — a globally flat series, or a step whose segments are numerically constant, as cpt_simulate(sd = 0) produces once any rounding is added. stepR's heterogeneous variance estimator aborts the R session on such input rather than raising an error, so it cannot be caught. "gauss" handles the whole range.

...

Additional arguments passed to stepR::stepFit().

Value

A ggcpt object. The changepoints tibble carries ci_lower/ci_upper (confidence interval for each changepoint location) and the data tibble carries the SMUCE step fit in its fitted column.

References

Frick K, Munk A, Sieling H (2014). “Multiscale change point inference.” Journal of the Royal Statistical Society: Series B, 76(3), 495–580.

Pein F, Sieling H, Munk A (2017). “Heterogeneous change point inference.” Journal of the Royal Statistical Society: Series B, 79(4), 1207–1227.

Examples



set.seed(2026)
x <- c(rnorm(100), rnorm(100, 3))
res <- smuce_wrapper(x)
res$changepoints
ggplot2::autoplot(res, show_ci = TRUE)



Self-normalisation wrapper (SNSeg)

Description

Wraps SNSeg::SNSeg_Uni() (Zhao, Jiang and Shao, 2022): self-normalised segmentation with nested local windows. Self-normalisation avoids estimating the long-run variance, is robust to temporal dependence, and detects changes in general parameters — mean, variance, quantiles, autocorrelation, or bivariate correlation — within one framework.

Usage

sn_wrapper(
  x,
  parameter = c("mean", "variance", "acf", "bivcor"),
  confidence = 0.9,
  grid_size = NULL,
  ...
)

Arguments

x

A numeric vector (or a two-column matrix for parameter = "bivcor").

parameter

Which parameter to test for changes: "mean", "variance", "acf", or "bivcor" (bivariate correlation). Defaults to "mean".

confidence

Confidence level of the self-normalised test, one of 0.9, 0.95, 0.99, 0.995 or 0.999. Defaults to 0.9.

grid_size

Grid size controlling the local-window sweep; when NULL the engine's default is used.

...

Additional arguments passed to SNSeg::SNSeg_Uni().

Value

A ggcpt object. About 20 observations are needed for the nested local windows at the default grid_size; a constant series returns an empty result rather than an engine error.

References

Zhao Z, Jiang F, Shao X (2022). “Segmenting time series via self-normalisation.” Journal of the Royal Statistical Society: Series B, 84(5), 1699–1725.

Examples



set.seed(2026)
res <- sn_wrapper(c(rnorm(150), rnorm(150, 3)))
res$changepoints



Changepoint detection stat

Description

Runs changepoint detection inside the ggplot pipeline. Useful for quick exploration: ggplot(df, aes(t, y)) + geom_line() + stat_changepoint(method = "pelt"). Draws vertical lines at detected changepoint locations.

Usage

stat_changepoint(
  mapping = NULL,
  data = NULL,
  geom = "vline",
  position = "identity",
  ...,
  method = "pelt",
  change_in = "mean",
  na.rm = FALSE,
  show.legend = NA
)

Arguments

mapping

Aesthetic mappings.

data

A data frame.

geom

The geometric object to use (default: "vline"). The stat computes a single xintercept per changepoint, so only geoms that consume that aesthetic fit — "vline" and "rug". A geom needing x/y, such as "point", errors because the stat drops those aesthetics.

position

Position adjustment.

...

Other arguments passed to the geom.

method

Detection method (passed to cpt_detect).

change_in

What to detect change in (passed to cpt_detect).

na.rm

If FALSE, missing values are removed.

show.legend

Whether to show legend.

Value

A ggplot layer.


Bai-Perron structural break wrapper (strucchange)

Description

Wraps strucchange::breakpoints() (Zeileis et al., 2002), the dynamic-programming implementation of the Bai and Perron (1998, 2003) multiple structural break estimator. Called with a bare numeric vector it dates mean shifts (y ~ 1); called with a formula and data it dates breaks in arbitrary regression coefficients. Break-date confidence intervals from confint() populate ci_lower/ci_upper and render via autoplot(show_ci = TRUE).

Usage

strucchange_wrapper(
  x,
  data = NULL,
  breaks = NULL,
  h = 0.15,
  conf_level = 0.95,
  ...
)

Arguments

x

A numeric vector (mean-shift mode), or a model formula (regression mode; supply data too).

data

Optional data frame for formula input.

breaks

Maximum number of breaks; when NULL the number is chosen by BIC.

h

Minimal segment size, as a fraction of the sample size (or an integer count). Defaults to 0.15.

conf_level

Confidence level for the break-date intervals. Defaults to 0.95.

...

Additional arguments passed to strucchange::breakpoints().

Value

A ggcpt object with ci_lower/ci_upper columns on the changepoints tibble.

Result size

$fit is the breakpoints object itself, and that object is quadratic in the series length: it keeps RSS.triang, the triangular table of segment residual sums of squares, which is what lets strucchange return the optimal segmentation for any number of breaks without refitting. Measured here, the whole result is about 1.7 MB at n = 200, 5.9 MB at n = 400 and 22.6 MB at n = 800 — roughly four times larger each time the series doubles — and that one table outweighs everything else in the fit put together, by a margin that widens as the series grows. A single fit is not a problem; a few hundred of them are, so when running this engine over a panel with cpt_batch() keep what you need (res$changepoints) rather than the whole list of results. No other engine here behaves this way: the median result across the other thirty is under ten times the size of the series it was given.

References

Bai J, Perron P (2003). “Computation and analysis of multiple structural change models.” Journal of Applied Econometrics, 18(1), 1–22.

Zeileis A, Leisch F, Hornik K, Kleiber C (2002). “strucchange: An R package for testing for structural change in linear regression models.” Journal of Statistical Software, 7(2), 1–38.

Examples


set.seed(2026)
res <- strucchange_wrapper(c(rnorm(100), rnorm(100, 3)))
res$changepoints


Summary of a ggcpt object

Description

Provides a human-readable digest of a changepoint detection result, including the segment table with levels and lengths, total cost, penalty, and runtime.

Usage

## S3 method for class 'ggcpt'
summary(object, ...)

## S3 method for class 'summary.ggcpt'
print(x, ...)

Arguments

object

A ggcpt object.

...

Additional arguments (ignored).

x

A summary.ggcpt object (for print()).

Value

A list with class summary.ggcpt containing the summary.


TGUH wrapper

Description

Wraps the breakfast package for Tail-Greedy Unbalanced-Haar detection, with information-criterion model selection.

Usage

tguh_wrapper(x, ...)

Arguments

x

A numeric vector.

...

Additional arguments passed to breakfast::breakfast().

Value

A ggcpt object.


ggchangepoint theme

Description

A minimal, publication-ready ggplot2 theme for changepoint plots.

Usage

theme_ggcpt(base_size = 11, base_family = "")

Arguments

base_size

Base font size. Defaults to 11.

base_family

Base font family. Defaults to "".

Value

A ggplot2 theme object.

Examples

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme_ggcpt()

Tidy a ggcpt object

Description

Returns the changepoints tibble (one row per changepoint).

Usage

## S3 method for class 'ggcpt'
tidy(x, ...)

Arguments

x

A ggcpt object.

...

Additional arguments (ignored).

Value

A tibble with columns cp, cp_value, and any method-specific columns.


WBS2 wrapper — Wild Binary Segmentation 2

Description

Wraps the breakfast package's WBS2 solution path with steepest-drop-to-low-levels (SDLL) model selection.

Usage

wbs2_wrapper(x, ...)

Arguments

x

A numeric vector.

...

Additional arguments passed to breakfast::breakfast().

Value

A ggcpt object.


WBS wrapper — Wild Binary Segmentation

Description

Wraps the wbs package for randomised changepoint detection via Wild Binary Segmentation.

Usage

wbs_wrapper(x, n_intervals = 5000, threshold = NULL, seed = NULL, ...)

Arguments

x

A numeric vector.

n_intervals

Number of random intervals. Defaults to 5000.

threshold

Manual threshold for detection. If NULL, model selection uses the strengthened Schwarz Information Criterion (sSIC).

seed

Optional seed for reproducibility.

...

Additional arguments passed to wbs::wbs().

Value

A ggcpt object.