fitverse: Fit Probability Distributions to Univariate Continuous Data

View source: R/fitverse.R

fitverseR Documentation

Fit Probability Distributions to Univariate Continuous Data

Description

The primary function of the FitVerse package. Given a numeric data vector, fitverse() fits one or more parametric probability distributions, ranks them by an information criterion, selects the best-fitting model, computes goodness-of-fit statistics, and optionally produces a publication-quality diagnostic plot.

Three estimation methods are supported: Maximum Likelihood Estimation ("MLE"), Method of Moments ("MOM"), and L-Moments ("LMOM"). When multiple methods are requested, all results are combined into a single ranking table and the global best model is returned.

Tip: For a point-and-click experience, launch the built-in interactive Shiny application with FitVerseApp().

Usage

fitverse(x,
         dists       = "all",
         method      = "MLE",
         criterion   = "AIC",
         xlab        = "x",
         plot        = TRUE,
         interactive = FALSE,
         top_n       = 3L,
         progress    = NULL,
         verbose     = TRUE,
         ...)

Arguments

x

A numeric vector of observations. At least 4 finite values are required. Non-finite values (NA, NaN, Inf, -Inf) are removed automatically before fitting; a message is printed if any are found.

dists

Character vector of distribution keys to try, or "all" (default) to attempt every distribution whose support is compatible with the data. Use fitverse_distributions() to see all valid keys. Example: dists = c("gamma", "lognormal", "weibull").

method

Character vector specifying which estimation method(s) to use. One or more of:

"MLE"

Maximum Likelihood Estimation via numerical optimisation (fitdistrplus or custom stats::optim). Available for all 52 distributions.

"MOM"

Method of Moments. Uses closed-form expressions where available; numerical solution otherwise. Available for most of the 52 distributions.

"LMOM"

L-Moment estimation via lmomco. Available for distributions with L-moment parameter estimators.

When multiple methods are supplied (e.g. method = c("MLE", "MOM")), all fits are combined and ranked together. Default: "MLE".

criterion

Character: the information criterion used for ranking and best-model selection. Either "AIC" (default) or "BIC".

AIC is recommended for exploratory analysis and prediction; BIC imposes a stronger penalty for model complexity and is preferred when the goal is identifying the true generating distribution.

xlab

Character: a label for the data variable used in plot axis titles and the auto-generated report. Default "x". Example: xlab = "Annual maximum flood (m^3/s)".

plot

Logical: should a diagnostic plot be produced and printed? Default TRUE. Set to FALSE for batch workflows or when embedding in scripts. The plot can always be regenerated later with plot.fitverse().

interactive

Logical: if TRUE and the plotly package is installed, produces an interactive HTML figure instead of a static ggplot2 image. Default FALSE.

top_n

Integer: number of top-ranked distributions to overlay on the density panel of the diagnostic plot. The best-fit model is always drawn as a solid line; the remaining top_n - 1 are drawn as dashed lines. Default 3. Range: 1 to nrow(ranking).

progress

Optional function of the form function(p) where p is a numeric value in [0, 1] indicating the proportion of work completed. Called at several points during fitting. Useful for updating a shiny progress bar. Default NULL (no callback). Example: progress = function(p) shiny::setProgress(p).

verbose

Logical: print progress messages to the console? Default TRUE. Set to FALSE in batch workflows or when running inside shiny.

...

Additional arguments passed to plot.fitverse().

Details

Workflow

fitverse() executes the following steps:

  1. Validate and clean – removes non-finite values; checks that at least 4 observations remain.

  2. Filter distributions – distributions whose support is incompatible with the data (e.g. positive-only Gamma when data contains negative values) are silently excluded.

  3. Fit – calls fit_mle_all(), fit_mom_all(), and/or fit_lmom_all() according to method.

  4. Goodness-of-fit – attaches Kolmogorov-Smirnov (KS), Anderson-Darling (AD), and Cramer-von Mises (CvM) test results to each fit result.

  5. Rank – builds a table ordered by criterion (ascending AIC or BIC).

  6. Select – chooses the model with the lowest AIC (or BIC).

  7. Summarise – computes compute_data_summary() and stores it in the returned object.

  8. Plot (optional) – calls plot.fitverse().

Estimation methods

MLE

Maximises the log-likelihood \ell(\boldsymbol\theta) = \sum_{i=1}^n \log f(x_i; \boldsymbol\theta). Implemented via fitdistrplus::fitdist() with bounded L-BFGS-B optimisation where parameter constraints exist.

MOM

Equates the first k sample moments to their theoretical counterparts and solves for the k parameters. Closed-form solutions are used where available (Normal, Gamma, Log-Normal, Exponential, Beta, Logistic, Uniform, Gumbel, Pareto, Inverse Gamma); numerical solution via stats::optimise() for Weibull and Log-Logistic. fitdistrplus MME is used for standard stats distributions.

LMOM

Equates sample L-moments (linear combinations of order statistics) to their theoretical counterparts. L-moments are more robust to outliers than conventional moments and are widely used in hydrology. Implemented via lmomco; available for Normal, Gamma, Exponential, Log-Normal, Weibull, GEV, GLO, Gumbel, Logistic, and Log-Logistic. Reference: Hosking (1990).

Model selection

The best-fit model is the one with the lowest AIC (or BIC) across all fitted distributions and methods. Delta AIC values in the ranking table quantify evidence against each model relative to the best: models with Delta AIC < 2 have "substantial support", 4–7 "considerably less", and > 10 "essentially none" (Burnham and Anderson, 2002).

Goodness-of-fit tests

Three non-parametric tests are applied to the best-fit model:

Kolmogorov-Smirnov (KS)

Measures the maximum absolute difference between the empirical and fitted CDFs. Conservative; not recommended as the primary criterion.

Anderson-Darling (AD)

Gives extra weight to the distribution tails. More powerful than KS for detecting tail departures. Implemented via goftest.

Cramer-von Mises (CvM)

Integrates the squared difference between empirical and fitted CDFs. Implemented via goftest.

A large p-value (> 0.05) indicates insufficient evidence to reject the fitted distribution.

Value

An S3 object of class "fitverse". It is a named list with the following elements:

best_fit

Named list describing the best-fitting model, with elements:

dist_key

Character: distribution key (e.g. "gamma").

method

Character: estimation method ("MLE", "MOM", or "LMOM").

params

Named numeric vector of parameter estimates.

loglik

Numeric: maximised log-likelihood.

aic

Numeric: Akaike Information Criterion.

bic

Numeric: Bayesian Information Criterion.

n_params

Integer: number of estimated parameters.

n

Integer: sample size used.

converged

Logical: did the optimiser converge?

gof

Data frame of goodness-of-fit test results (Test, Statistic, P_value, Stars), or NULL if unavailable.

all_fits

Named list of all fit-result lists, one per distribution-method combination. Keys are of the form "distkey_METHOD" (e.g. "gamma_MLE").

ranking

Data frame with columns: Rank, Distribution, Method, N_params, LogLik, AIC, Delta_AIC, BIC, Delta_BIC, KS_p, AD_p, Converged, dist_key. Ordered by the chosen criterion (ascending).

data

Numeric vector: the cleaned input data.

n

Integer: number of finite observations used.

xlab

Character: the variable label.

data_summary

Named list from compute_data_summary(): n, n_missing, mean, sd, cv, median, iqr, skewness, kurtosis, min, max, range, q25, q75.

criterion

Character: "AIC" or "BIC".

method

Character vector: method(s) used.

call

The matched function call.

The object is returned invisibly. Use print(), summary(), plot(), coef(), logLik(), AIC(), and BIC() for standard S3 method access.

Author(s)

Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj

References

Burnham, K. P. and Anderson, D. R. (2002). Model Selection and Multimodel Inference (2nd ed.). Springer.

Delignette-Muller, M. L. and Dutang, C. (2015). fitdistrplus: An R package for fitting distributions. Journal of Statistical Software, 64(4), 1–34. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.18637/jss.v064.i04")}

Hosking, J. R. M. (1990). L-moments: Analysis and estimation of distributions using linear combinations of order statistics. Journal of the Royal Statistical Society, Series B, 52(1), 105–124.

Akaike, H. (1974). A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19(6), 716–723.

See Also

compare_dists for a ranking table only (no plot).
fitverse_distributions to list all supported distributions.
plot.fitverse, summary.fitverse, bootstrap_ci, return_level, generate_report.

Examples

## -----------------------------------------------------------
## Example 1: Basic MLE fit -- three distributions
## -----------------------------------------------------------
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)

fit <- fitverse(x,
                dists   = c("gamma", "lognormal", "weibull"),
                method  = "MLE",
                xlab    = "Waiting time (s)",
                plot    = FALSE,
                verbose = FALSE)

print(fit)
coef(fit)        # parameter estimates
AIC(fit)         # AIC of the best-fit model
logLik(fit)      # log-likelihood

## -----------------------------------------------------------
## Example 2: All three estimation methods, ranked by BIC
## -----------------------------------------------------------

fit2 <- fitverse(x,
                 method    = c("MLE", "MOM", "LMOM"),
                 criterion = "BIC",
                 plot      = FALSE,
                 verbose   = FALSE)
summary(fit2)


## -----------------------------------------------------------
## Example 3: Automatic best-fit selection across all distributions
## -----------------------------------------------------------

set.seed(7)
x3 <- rlnorm(500, meanlog = 1.5, sdlog = 0.6)

fit3 <- fitverse(x3,
                 xlab    = "Insurance claim size",
                 method  = "MLE",
                 plot    = FALSE,
                 verbose = FALSE)
fit3$ranking[1:5, c("Distribution","Method","AIC","Delta_AIC","AD_p")]


## -----------------------------------------------------------
## Example 4: Accessing the data summary
## -----------------------------------------------------------

fit4 <- fitverse(x, plot = FALSE, verbose = FALSE)
fit4$data_summary$mean
fit4$data_summary$skewness


FitVerse documentation built on Dec. 1, 2026, 1:07 a.m.