| Type: | Package |
| Title: | Parametric Distribution Fitting and Analysis |
| Version: | 1.0-1 |
| Date: | 2026-08-09 |
| Description: | Provides a unified, user-friendly interface for fitting parametric probability distributions to continuous univariate data. 'FitVerse' supports 52 distribution families spanning symmetric, right-skewed, heavy-tailed, bounded, and extreme-value shapes, and three estimation methods: Maximum Likelihood Estimation (MLE), Method of Moments (MOM), and L-Moments (L-MOM). Automatic best-fit selection is performed using AIC, BIC, and goodness-of-fit tests (Kolmogorov-Smirnov, Anderson-Darling, Cramer-von Mises (CvM)). Every fitted model produces a publication-quality diagnostic plot: a histogram overlaid with the fitted density curve and the estimated PDF formula annotated directly on the figure. An optional interactive version is produced via 'plotly'. Additional tools include bootstrap confidence intervals for parameter estimates and return levels, batch fitting across multiple columns for automated workflows and web-upload use cases, JSON serialisation for integration with 'Shiny' web applications, and automated HTML/PDF report generation. 'FitVerse' is designed to support data characterisation in survey sampling, hydrology, and actuarial workflows, where identifying the underlying distribution of a variable is a prerequisite for downstream modelling and inference. L-moment estimation follows Hosking (1990) <doi:10.1111/j.2517-6161.1990.tb01775.x> and Hosking and Wallis (1997, ISBN:9780521430456). Model selection via AIC follows Akaike (1974) <doi:10.1109/TAC.1974.1100705> and via BIC follows Schwarz (1978) <doi:10.1214/aos/1176344136>. Bootstrap confidence intervals follow Efron and Hastie (2016, ISBN:9781107149892). |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| Depends: | R (≥ 4.1.0) |
| Imports: | stats, graphics, grDevices, utils, tools, actuar (≥ 3.1.0), mc2d (≥ 0.1.18), evd (≥ 2.3.3), sn (≥ 2.1.0), fitdistrplus (≥ 1.1.0), lmomco (≥ 2.3.7), ggplot2 (≥ 3.4.0), goftest (≥ 1.2.3), gridExtra (≥ 2.3) |
| Suggests: | shiny (≥ 1.7.0), bslib (≥ 0.5.0), DT, plotly (≥ 4.10.0), testthat (≥ 3.0.0), knitr (≥ 1.40), rmarkdown (≥ 2.20), kableExtra, jsonlite (≥ 1.8.0), base64enc, MASS, GeneralizedHyperbolic, truncnorm |
| VignetteBuilder: | knitr |
| RoxygenNote: | 7.3.2 |
| NeedsCompilation: | no |
| Packaged: | 2026-08-22 01:24:26 UTC; karunareddy |
| Author: | Karuna G. Reddy |
| Maintainer: | Karuna G. Reddy <karuna.reddy@auckland.ac.nz> |
| Repository: | CRAN |
| Date/Publication: | 2026-09-01 14:20:02 UTC |
FitVerse: Parametric Distribution Fitting and Analysis
Description
FitVerse provides a unified, user-friendly interface for fitting parametric probability distributions to continuous univariate data. The package supports 52 distribution families spanning symmetric, right-skewed, heavy-tailed, bounded, and extreme-value shapes, and three estimation methods: Maximum Likelihood Estimation (MLE), Method of Moments (MOM), and L-Moments (LMOM).
Automatic best-fit selection is performed using AIC and BIC, supplemented by four goodness-of-fit tests: Kolmogorov-Smirnov (KS), Anderson-Darling (AD), Cramer-von Mises (CvM), and Chi-Squared.
Every fitted model produces a publication-quality diagnostic plot: a histogram
overlaid with the fitted density curve and the estimated PDF formula annotated
directly on the figure. Additional diagnostic panels (Q-Q, P-P, CDF, Survival,
Hazard, and Cumulative Hazard) are available via plot.fitverse().
FitVerse is designed as the data-characterisation layer of the OptiStrata ecosystem, with seamless handoff to stratifyR for optimal stratification of survey populations.
Main fitting functions
fitverse | Fit distributions to individual observations |
fitverse_grouped | Fit distributions to grouped/interval data |
fitverse_censored | Fit distributions to censored data |
fitverse_batch | Fit all columns of a data frame |
compare_dists | Return the ranked comparison table only |
fitverse_distributions | List all 52 supported distributions |
Probability tools
dfitverse | Density of the best-fit distribution |
pfitverse | CDF of the best-fit distribution |
qfitverse | Quantile function of the best-fit distribution |
rfitverse | Random samples from the best-fit distribution |
return_level | T-year return levels from the fitted model |
lmrd | L-moment ratio diagram |
ev_threshold | Extreme-value threshold stability plots |
Inference and reporting
bootstrap_ci | Bootstrap confidence intervals for parameters |
generate_report | Produce a self-contained HTML or PDF report |
save_plot | Save the diagnostic plot to a file |
to_json | Serialise a fitverse object to JSON |
Sample datasets
FitVerse_datasets | Bundled CSV files for individual and grouped data |
read_grouped_csv | Read a grouped-data CSV into list format |
S3 methods for "fitverse" objects
print.fitverse | Concise best-fit summary |
summary.fitverse | Full diagnostic report to the console |
plot.fitverse | Diagnostic plots (density, Q-Q, P-P, CDF, etc.) |
coef.fitverse | Extract parameter estimates |
logLik.fitverse | Extract log-likelihood |
AIC.fitverse | Extract AIC |
BIC.fitverse | Extract BIC |
as.list.fitverse | Convert to a serialisation-ready list |
Supported distributions (52 families)
| Shape | Distribution | Key |
| Symmetric | Normal | normal |
| Symmetric | Logistic | logistic |
| Symmetric | Cauchy | cauchy |
| Symmetric | Laplace | laplace |
| Symmetric | Student-t (location-scale) | student_t |
| Symmetric | Truncated Normal | truncnorm |
| Asymmetric | Skew-Normal | skewnormal |
| Asymmetric | Generalised Normal | gnorm |
| Asymmetric | Asymmetric Laplace | alaplace |
| Asymmetric | Johnson SU | johnsonsu |
| Right-skewed | Gamma | gamma |
| Right-skewed | Gamma (3-parameter) | gamma3 |
| Right-skewed | Log-Normal | lognormal |
| Right-skewed | Log-Normal (3-parameter) | lognormal3 |
| Right-skewed | Exponential | exponential |
| Right-skewed | Exponentiated Exponential | expexp |
| Right-skewed | Weibull (2-parameter) | weibull |
| Right-skewed | Weibull (3-parameter) | weibull3p |
| Right-skewed | Exponentiated Weibull | expweibull |
| Right-skewed | Log-Logistic | loglogistic |
| Right-skewed | Inverse Gaussian | invgaussian |
| Right-skewed | Inverse Gamma | invgamma |
| Right-skewed | Inverse Weibull | invweibull |
| Right-skewed | Gompertz | gompertz |
| Right-skewed | Birnbaum-Saunders | birnbaum_saunders |
| Right-skewed | Rayleigh | rayleigh |
| Right-skewed | Half-Normal | halfnormal |
| Right-skewed | Lindley | lindley |
| Right-skewed | Nakagami | nakagami |
| Heavy-tailed | Pareto | pareto |
| Heavy-tailed | Burr XII | burr |
| Heavy-tailed | Lomax (Pareto Type II) | lomax |
| Heavy-tailed | Paralogistic | paralogistic |
| Heavy-tailed | Dagum | dagum |
| Heavy-tailed | GB2 (Generalised Beta II) | gb2 |
| Heavy-tailed | Normal Inverse Gaussian | nig |
| Heavy-tailed | Generalised Hyperbolic | ghyp |
| Heavy-tailed | Generalised Gamma | gengamma |
| Extreme value | Generalised Extreme Value | gev |
| Extreme value | Gumbel | gumbel |
| Extreme value | Generalised Pareto | gpd |
| Extreme value | Generalised Logistic | glo |
| Extreme value | Pearson Type III | pearson3 |
| Extreme value | Log-Pearson Type III | lpearson3 |
| Extreme value | Kappa-4 | kap4 |
| Extreme value | Wakeby | wakeby |
| Bounded | Beta | beta |
| Bounded | Uniform | uniform |
| Bounded | Triangular | triangular |
| Bounded | Right Triangular | rtriangle |
| Bounded | PERT | pert |
| Bounded | Kumaraswamy | kumaraswamy
|
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz (University of Auckland, New Zealand)
M. G. M. Khan mgm.khan@usp.ac.fj (University of the South Pacific, Fiji)
Maintainer: Karuna G. Reddy karuna.reddy@auckland.ac.nz
References
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. doi:10.1111/j.2517-6161.1990.tb01775.x
Delignette-Muller, M. L. and Dutang, C. (2015). fitdistrplus: An R package for fitting distributions. Journal of Statistical Software, 64(4), 1–34. doi:10.18637/jss.v064.i04
Akaike, H. (1974). A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19(6), 716–723. doi:10.1109/TAC.1974.1100705
See Also
fitverse, fitverse_distributions,
fitverse_grouped, FitVerse_datasets,
fitdistrplus, actuar, lmomco
Examples
## Quick start: fit three distributions to simulated Gamma data
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)
## See all 52 supported distributions
fitverse_distributions()
Launch the FitVerse Interactive Shiny Application
Description
Opens the FitVerse web interface in the default browser. The app provides a point-and-click interface for uploading data, fitting distributions, inspecting diagnostic plots, and downloading results — without writing any R code.
Usage
FitVerseApp(...)
Arguments
... |
Additional arguments passed to |
Details
Requires the shiny package (listed in Suggests).
An informative error is raised if it is not installed.
The app files are stored in inst/app/ and located at runtime via
system.file("app", package = "FitVerse").
Value
Called for its side effect (launches a Shiny app); returns NULL
invisibly.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse for the programmatic fitting interface.
Examples
if (interactive()) {
FitVerseApp()
}
Sample Datasets Bundled with FitVerse
Description
FitVerse includes several comma-separated value (CSV) files in
inst/extdata/ that can be used to explore the package's fitting
functions. All files are accessed with system.file().
Individual-observation datasets (for fitverse())
annual_max_flows.csv-
Annual maximum daily peak flows (m
^3/s) for the Rewa River at Navolau, Fiji, covering a 75-year record (1950–2024). The data are right-skewed; Gumbel, GEV, Log-Pearson III, and Log-Normal are natural candidates. wind_speeds.csv-
Daily maximum wind gust speeds (m/s) recorded at Nadi Airport, Fiji, over 200 days (2020–2024). Weibull and Rayleigh distributions are commonly used for wind data.
failure_times.csv-
Failure times (hours) from a life test of 150 aluminium electrolytic capacitors under 85
{}^\circC stress. Weibull, Gamma, Log-Normal, and Birnbaum-Saunders are typical reliability choices. insurance_claims.csv-
Residential property insurance claim amounts (in thousands of USD) from 180 claims settled by Pacific Insurance Ltd between 2018 and 2024. Log-Normal, Gamma, and Pareto distributions are common in loss modelling.
concrete.csv-
Compressive strength (MPa) and mix-design variables for 1030 concrete specimens (UCI Machine Learning Repository). The
Strengthcolumn is suitable for fitting; Normal, Gamma, and Weibull are plausible choices.
Grouped / interval-censored datasets (for fitverse_grouped())
rainfall_grouped.csv-
Annual maximum daily rainfall (mm) at Suva, Fiji, summarised into a frequency table with columns
midpointandcount(80 years of record). failure_times_grouped.csv-
Failure times for 120 electronic components given as an interval frequency table with columns
lower,upper, andcount. insurance_losses_grouped.csv-
Property insurance claim amounts for 250 claims given as an interval frequency table with columns
lower,upper, andcount.
Format
Each file is a plain-text CSV with a column-name header row. Lines
beginning with # are comments describing the dataset. All
numeric values use the standard decimal point.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse for fitting to individual observations.
fitverse_grouped for fitting to grouped / interval data.
Examples
## Annual maximum flows
path <- system.file("extdata", "annual_max_flows.csv", package = "FitVerse")
x <- read.csv(path, comment.char = "#")$peak_flow_m3s
summary(x)
fit <- fitverse(x, xlab = "Peak flow (m3/s)", plot = FALSE)
print(fit)
## Grouped rainfall data
gpath <- system.file("extdata", "rainfall_grouped.csv", package = "FitVerse")
dat <- read_grouped_csv(gpath)
gfit <- fitverse_grouped(midpoints = dat$midpoints, counts = dat$counts,
xlab = "Rainfall (mm)")
print(gfit)
Bootstrap Confidence Intervals for Distribution Parameters
Description
Computes non-parametric percentile bootstrap confidence intervals for the
parameters of the best-fit distribution in a fitverse object.
Optionally also bootstraps confidence intervals for T-year return levels.
Usage
bootstrap_ci(fit,
B = 999L,
conf = 0.95,
return_periods = NULL,
progress = NULL,
seed = NULL,
verbose = TRUE)
## S3 method for class 'fitverse_bootstrap'
print(x, ...)
Arguments
fit |
An object of class |
B |
Integer: number of bootstrap replicates. Default |
conf |
Numeric in |
return_periods |
Numeric vector of return periods for which bootstrap CIs on return
levels should be computed. |
progress |
Optional function of the form |
seed |
Integer or |
verbose |
Logical: print a progress message? Default |
x |
An object of class |
... |
Currently unused. |
Details
Algorithm
The non-parametric percentile bootstrap proceeds as follows:
Draw
Bbootstrap samples of sizenwith replacement from the observed data.Re-fit the same distribution and estimation method to each sample, using the same internal engine as
fitverse().Collect the
B \times kmatrix of parameter estimates (wherekis the number of parameters).For each parameter, report the
\alpha/2and1 - \alpha/2empirical percentiles of the bootstrap distribution as the lower and upper confidence bounds.
Replicates that fail to converge are excluded; a warning is issued if more than 10% fail.
Return-level CIs
When return_periods is supplied, the T-year return level is computed
for each bootstrap replicate using return_level(), and the
percentile CI is reported for each T.
Value
An S3 object of class "fitverse_bootstrap" with the following
elements:
params_ci-
Data frame with one row per parameter and columns:
parameter,estimate,lower,upper,se_boot(bootstrap standard error). return_level_ci-
Data frame (or
NULLifreturn_periods = NULL) with columns:T,return_level,lower,upper. boot_params-
Numeric matrix of dimension
B_{eff} \times k: all successful bootstrap parameter estimates. Useful for plotting bootstrap distributions. BInteger: number of replicates requested.
B_effInteger: number of successful replicates.
confNumeric: confidence level.
dist_keyCharacter: distribution key.
methodCharacter: estimation method.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
References
Efron, B. and Tibshirani, R. J. (1993). An Introduction to the Bootstrap. Chapman and Hall, New York.
Davison, A. C. and Hinkley, D. V. (1997). Bootstrap Methods and Their Application. Cambridge University Press.
See Also
return_level for point estimates without CIs.
fitverse for the initial fitting step.
Examples
set.seed(42)
x <- rgamma(200, shape = 2, rate = 0.5)
fit <- fitverse(x, dists = "gamma", plot = FALSE, verbose = FALSE)
boot <- bootstrap_ci(fit, B = 499, conf = 0.95, seed = 1, verbose = FALSE)
print(boot)
# Parameter CI data frame
boot$params_ci
# With return-level CIs
boot2 <- bootstrap_ci(fit, B = 499, return_periods = c(10, 50, 100),
seed = 1, verbose = FALSE)
boot2$return_level_ci
Compare Distribution Fits and Return a Ranking Table
Description
Fits one or more parametric distributions to a numeric vector and returns
an ordered ranking table without producing a plot or a full fitverse
object. Use this function when you want a quick tabular comparison and
do not need the fitted-object infrastructure.
Usage
compare_dists(x,
dists = "all",
method = "MLE",
criterion = "AIC",
xlab = "x",
verbose = TRUE)
Arguments
x |
A numeric vector of observations. Non-finite values are removed automatically before fitting. |
dists |
Character vector of distribution keys, or |
method |
Character vector: one or more of |
criterion |
|
xlab |
Character: a label for the data variable, passed through to any
downstream functions. Default |
verbose |
Logical: print progress messages? Default |
Details
compare_dists() calls the same internal fitting engine as
fitverse() but skips GoF test computation, data-summary
computation, and plotting. It is therefore faster and better suited to
exploratory screening of many distributions or methods.
The returned data frame can be used directly with kable
or datatable for reporting.
Value
A data frame with one row per distribution-method combination, ordered by the chosen information criterion (ascending), with columns:
- Rank
Integer rank (1 = best).
- Distribution
Full distribution name.
- Method
Estimation method (
"MLE","MOM", or"LMOM").- N_params
Number of free parameters.
- LogLik
Maximised log-likelihood.
- AIC
Akaike Information Criterion.
- Delta_AIC
AIC difference relative to the best model.
- BIC
Bayesian Information Criterion.
- Delta_BIC
BIC difference relative to the best model.
- Converged
Logical: did the optimiser converge?
- dist_key
Internal distribution key (character).
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse for a full fitted object plus diagnostic plot.
Examples
set.seed(1)
x <- rgamma(200, shape = 3, rate = 0.5)
tbl <- compare_dists(x,
dists = c("gamma", "lognormal", "weibull", "exponential"),
method = "MLE",
verbose = FALSE)
head(tbl)
Compute and Print a Descriptive Statistics Summary
Description
compute_data_summary() computes a comprehensive set of descriptive
statistics for a numeric vector and returns them as a named list.
print_data_summary() formats and prints that list to the console.
These functions are called automatically by fitverse() and
summary.fitverse(), but can also be used independently for
exploratory data analysis.
Usage
compute_data_summary(x, xlab = "x", n_raw = NULL)
print_data_summary(ds)
Arguments
x |
A numeric vector, already cleaned of non-finite values (or not – the function removes them internally). |
xlab |
Character: variable name, stored in the returned list for labelling.
Default |
n_raw |
Integer or |
ds |
A named list as returned by |
Details
Skewness and kurtosis are computed using the bias-corrected (unbiased) estimators:
g_1 = \frac{n}{(n-1)(n-2)} \sum_{i=1}^n
\left(\frac{x_i - \bar{x}}{s}\right)^3
g_2 = \frac{n(n+1)}{(n-1)(n-2)(n-3)}
\sum_{i=1}^n \left(\frac{x_i - \bar{x}}{s}\right)^4
- \frac{3(n-1)^2}{(n-2)(n-3)}
These correspond to the skewness and kurtosis functions in
the moments package (type 3 in e1071) and are consistent with
the convention in Applied Statistics textbooks. The Normal
distribution has skewness 0 and excess kurtosis 0.
Value
compute_data_summary() returns a named list with the following
elements:
nInteger: number of finite (non-missing) observations used.
n_missingInteger or
NA: number of non-finite values removed.meanArithmetic mean.
sdStandard deviation (denominator
n-1).cvCoefficient of variation (
sd / mean).NAwhenmean == 0.medianSample median.
iqrInterquartile range (
Q_{0.75} - Q_{0.25}).skewnessSample skewness (Fisher's
g_1).kurtosisExcess kurtosis (Fisher's
g_2).minSample minimum.
maxSample maximum.
rangeRange (
max - min).q2525th percentile.
q7575th percentile.
xlabCharacter: the variable label.
print_data_summary() invisibly returns ds.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse (calls this automatically),
summary.fitverse.
Examples
set.seed(3)
x <- rlnorm(500, meanlog = 1, sdlog = 0.5)
ds <- compute_data_summary(x, xlab = "Claim amount", n_raw = 510)
print_data_summary(ds)
# Access individual statistics
ds$skewness
ds$cv
Density, CDF, Quantile, and Random Sampling for a Fitted Distribution
Description
Convenience functions that evaluate the probability density function (PDF),
cumulative distribution function (CDF), quantile function (inverse CDF),
and random-number generator for the best-fit distribution stored in a
fitverse object.
These follow the standard R d/p/q/r naming convention and delegate to
the underlying d*, p*, q*, and r* functions
for the best-fit distribution.
Usage
dfitverse(x, fit, log = FALSE)
pfitverse(q, fit, lower.tail = TRUE, log.p = FALSE)
qfitverse(p, fit, lower.tail = TRUE, log.p = FALSE)
rfitverse(n, fit)
Arguments
x |
Numeric vector of quantiles at which to evaluate the density. |
q |
Numeric vector of quantiles at which to evaluate the CDF. |
p |
Numeric vector of probabilities |
n |
Integer: number of random samples to generate. |
fit |
An object of class |
log, log.p |
Logical: if |
lower.tail |
Logical: if |
Details
The correct d/p/q/r functions are resolved via .lookup_dpqr(),
which follows a two-step priority:
-
Internal closed-form implementations (highest priority): GEV, Gumbel, GPD, Pearson III, Log-Pearson III, and GLO all use FitVerse's own vectorised implementations registered in
.FITVERSE_DPQR_OVERRIDES. This avoids any package-version signature issues with evd and provides full support for the new hydrological distributions that have no dedicated CRAN d/p/q/r package. -
Package namespace lookup: For all other distributions, stats functions are found via
match.fun(); Imports/Suggests packages (actuar, sn, mc2d) are resolved viagetExportedValue().
The estimated parameters are extracted from fit$best_fit$params
and passed as named arguments to the underlying function. This is
equivalent to calling, for example,
dgamma(x, shape = fit$best_fit$params["shape"], rate = fit$best_fit$params["rate"]).
Value
dfitverse()Numeric vector of density values.
pfitverse()Numeric vector of probabilities.
qfitverse()Numeric vector of quantiles.
rfitverse()Numeric vector of random samples.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
return_level for T-year return levels.
fitverse for the fitting step.
Examples
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
fit <- fitverse(x, dists = "gamma", plot = FALSE, verbose = FALSE)
# Density at x = 2
dfitverse(2, fit)
# Probability that X <= 5
pfitverse(5, fit)
# 90th percentile
qfitverse(0.90, fit)
# Generate 10 random samples
rfitverse(10, fit)
Custom d/p/q/r Functions for Additional Distributions
Description
Density, CDF, quantile, and random-generation functions for distribution families that are either unavailable on CRAN, parameterised differently from existing packages, or implemented from scratch for performance and consistency within FitVerse.
The following families are covered:
- Student-t (location-scale)
Three-parameter Student-t with location
\mu, scale\sigma > 0, and degrees of freedom\nu > 0:dstudent_t,pstudent_t,qstudent_t,rstudent_t.- Laplace
Symmetric double-exponential with location
\muand scaleb > 0:dlaplace,plaplace,qlaplace,rlaplace.- Inverse Gaussian
Two-parameter (mean
\mu > 0, shape\lambda > 0):dinvgaussian,pinvgaussian,qinvgaussian,rinvgaussian.- Lomax (Pareto Type II)
Shape
\alpha > 0and scale\lambda > 0:dlomax,plomax,qlomax,rlomax.- Generalised Gamma
Three-parameter generalisation of the Gamma (shape
p > 0, scaled > 0, powerb > 0):dgengamma,pgengamma,qgengamma,rgengamma.- Gompertz
Parameters
\alpha > 0and\beta > 0:dgompertz,pgompertz,qgompertz,rgompertz.- Birnbaum-Saunders (Fatigue-Life)
Shape
\alpha > 0and scale\beta > 0:dbirnbaum_saunders,pbirnbaum_saunders,qbirnbaum_saunders,rbirnbaum_saunders.- Rayleigh
Scale
\sigma > 0:drayleigh,prayleigh,qrayleigh,rrayleigh.- Half-Normal
Scale
\sigma > 0:dhalfnormal,phalfnormal,qhalfnormal,rhalfnormal.- Exponentiated Weibull
Shape parameters
shape1 > 0andshape2 > 0, scalescale > 0:dexpweibull,pexpweibull,qexpweibull,rexpweibull.- Three-Parameter Gamma
Gamma with location threshold
\gamma(shape\alpha > 0, scale\beta > 0, threshold\gamma):dgamma3,pgamma3,qgamma3,rgamma3.- Three-Parameter Log-Normal
Log-Normal with threshold
\gamma(meanlog\mu, sdlog\sigma > 0, threshold\gamma):dlnorm3,plnorm3,qlnorm3,rlnorm3.- Right Triangular
Special triangular with
minandmax, where the mode equalsmax:drtriangle,prtriangle,qrtriangle,rrtriangle.- Kumaraswamy
Bounded distribution with shape parameters
shape1 > 0andshape2 > 0on(0, 1):dkumaraswamy,pkumaraswamy,qkumaraswamy,rkumaraswamy.- Generalised Beta of the Second Kind (GB2)
Four-parameter family with
shape1 > 0,scale > 0,shape2 > 0,shape3 > 0:dgb2,pgb2,qgb2,rgb2.- Kappa Four-Parameter
Generalised extreme-value family with location
xi, scalealpha > 0, and shape parameterskappaandh:dkap4,pkap4,qkap4,rkap4.- Lindley
One-parameter distribution with
theta > 0:dlindley,plindley,qlindley,rlindley.- Generalised Normal
Three-parameter distribution with location
mu, scalesigma > 0, and shapebeta > 0:dgnorm,pgnorm,qgnorm,rgnorm.- Dagum
Three-parameter Burr Type III with
shape1 > 0,scale > 0,shape2 > 0:ddagum,pdagum,qdagum,rdagum.- Johnson SU
Four-parameter unbounded system with
gamma,delta > 0,xi,lambda > 0:djohnsonsu,pjohnsonsu,qjohnsonsu,rjohnsonsu.- Asymmetric Laplace
Three-parameter asymmetric Laplace with location
mu, scalesigma > 0, and asymmetrykappa > 0:dalaplace,palaplace,qalaplace,ralaplace.- Exponentiated Exponential
Two-parameter family with shape
alpha > 0and ratelambda > 0:dexpexp,pexpexp,qexpexp,rexpexp.- Normal-Inverse Gaussian (NIG)
Four-parameter family with location
mu, spreaddelta > 0, steepnessalpha > 0, and asymmetrybeta:dnig,pnig,qnig,rnig.- Wakeby
Five-parameter quantile-defined distribution with location
xi, scale parametersalphaandbeta, and shape parametersgammaanddelta:dwakeby,pwakeby,qwakeby,rwakeby.- Generalised Hyperbolic (GHyp)
Five-parameter family with
lambda,alpha > 0,beta,delta > 0,mu:dghyp,pghyp,qghyp,rghyp.- Truncated Normal
Normal distribution truncated to
[a, b]withmeanandsd > 0:dtruncnorm,ptruncnorm,qtruncnorm,rtruncnorm.- Nakagami
Two-parameter fading distribution with shape
m >= 0.5and spreadOmega > 0:dnakagami,pnakagami,qnakagami,rnakagami.
Usage
dstudent_t(x, nu, mu, sigma, log = FALSE)
pstudent_t(q, nu, mu, sigma)
qstudent_t(p, nu, mu, sigma)
rstudent_t(n, nu, mu, sigma)
dlaplace(x, mu, b, log = FALSE)
plaplace(q, mu, b)
qlaplace(p, mu, b)
rlaplace(n, mu, b)
dinvgaussian(x, mu, lambda, log = FALSE)
pinvgaussian(q, mu, lambda)
qinvgaussian(p, mu, lambda)
rinvgaussian(n, mu, lambda)
dlomax(x, alpha, lambda, log = FALSE)
plomax(q, alpha, lambda)
qlomax(p, alpha, lambda)
rlomax(n, alpha, lambda)
dgengamma(x, p, d, b, log = FALSE)
pgengamma(q, p, d, b)
qgengamma(prob, p, d, b)
rgengamma(n, p, d, b)
dgompertz(x, alpha, beta, log = FALSE)
pgompertz(q, alpha, beta)
qgompertz(p, alpha, beta)
rgompertz(n, alpha, beta)
dbirnbaum_saunders(x, alpha, beta, log = FALSE)
pbirnbaum_saunders(q, alpha, beta)
qbirnbaum_saunders(p, alpha, beta)
rbirnbaum_saunders(n, alpha, beta)
drayleigh(x, sigma, log = FALSE)
prayleigh(q, sigma, lower.tail = TRUE, log.p = FALSE)
qrayleigh(p, sigma, lower.tail = TRUE, log.p = FALSE)
rrayleigh(n, sigma)
dhalfnormal(x, sigma, log = FALSE)
phalfnormal(q, sigma, lower.tail = TRUE, log.p = FALSE)
qhalfnormal(p, sigma, lower.tail = TRUE, log.p = FALSE)
rhalfnormal(n, sigma)
dexpweibull(x, shape1, scale, shape2, log = FALSE)
pexpweibull(q, shape1, scale, shape2, lower.tail = TRUE, log.p = FALSE)
qexpweibull(p, shape1, scale, shape2, lower.tail = TRUE, log.p = FALSE)
rexpweibull(n, shape1, scale, shape2)
dgamma3(x, shape, scale, thres, log = FALSE)
pgamma3(q, shape, scale, thres, lower.tail = TRUE, log.p = FALSE)
qgamma3(p, shape, scale, thres, lower.tail = TRUE, log.p = FALSE)
rgamma3(n, shape, scale, thres)
dlnorm3(x, meanlog, sdlog, thres, log = FALSE)
plnorm3(q, meanlog, sdlog, thres, lower.tail = TRUE, log.p = FALSE)
qlnorm3(p, meanlog, sdlog, thres, lower.tail = TRUE, log.p = FALSE)
rlnorm3(n, meanlog, sdlog, thres)
drtriangle(x, min, max, log = FALSE)
prtriangle(q, min, max)
qrtriangle(p, min, max)
rrtriangle(n, min, max)
dkumaraswamy(x, shape1, shape2, log = FALSE)
pkumaraswamy(q, shape1, shape2)
qkumaraswamy(p, shape1, shape2)
rkumaraswamy(n, shape1, shape2)
dgb2(x, shape1, scale, shape2, shape3, log = FALSE)
pgb2(q, shape1, scale, shape2, shape3, lower.tail = TRUE, log.p = FALSE)
qgb2(p, shape1, scale, shape2, shape3, lower.tail = TRUE, log.p = FALSE)
rgb2(n, shape1, scale, shape2, shape3)
dkap4(x, xi, alpha, kappa, h, log = FALSE)
pkap4(q, xi, alpha, kappa, h, lower.tail = TRUE, log.p = FALSE)
qkap4(p, xi, alpha, kappa, h, lower.tail = TRUE, log.p = FALSE)
rkap4(n, xi, alpha, kappa, h)
dlindley(x, theta, log = FALSE)
plindley(q, theta, lower.tail = TRUE, log.p = FALSE)
qlindley(p, theta, lower.tail = TRUE, log.p = FALSE)
rlindley(n, theta)
dgnorm(x, mu, sigma, beta, log = FALSE)
pgnorm(q, mu, sigma, beta, lower.tail = TRUE, log.p = FALSE)
qgnorm(p, mu, sigma, beta, lower.tail = TRUE, log.p = FALSE)
rgnorm(n, mu, sigma, beta)
ddagum(x, shape1, scale, shape2, log = FALSE)
pdagum(q, shape1, scale, shape2, lower.tail = TRUE, log.p = FALSE)
qdagum(p, shape1, scale, shape2, lower.tail = TRUE, log.p = FALSE)
rdagum(n, shape1, scale, shape2)
djohnsonsu(x, gamma, delta, xi, lambda, log = FALSE)
pjohnsonsu(q, gamma, delta, xi, lambda, lower.tail = TRUE, log.p = FALSE)
qjohnsonsu(p, gamma, delta, xi, lambda, lower.tail = TRUE, log.p = FALSE)
rjohnsonsu(n, gamma, delta, xi, lambda)
dalaplace(x, mu, sigma, kappa, log = FALSE)
palaplace(q, mu, sigma, kappa, lower.tail = TRUE, log.p = FALSE)
qalaplace(p, mu, sigma, kappa, lower.tail = TRUE, log.p = FALSE)
ralaplace(n, mu, sigma, kappa)
dexpexp(x, alpha, lambda, log = FALSE)
pexpexp(q, alpha, lambda, lower.tail = TRUE, log.p = FALSE)
qexpexp(p, alpha, lambda, lower.tail = TRUE, log.p = FALSE)
rexpexp(n, alpha, lambda)
dnig(x, mu, delta, alpha, beta, log = FALSE)
pnig(q, mu, delta, alpha, beta, lower.tail = TRUE, log.p = FALSE)
qnig(p, mu, delta, alpha, beta, lower.tail = TRUE, log.p = FALSE)
rnig(n, mu, delta, alpha, beta)
dwakeby(x, xi, alpha, beta, gamma, delta, log = FALSE)
pwakeby(q, xi, alpha, beta, gamma, delta, lower.tail = TRUE, log.p = FALSE)
qwakeby(p, xi, alpha, beta, gamma, delta, lower.tail = TRUE, log.p = FALSE)
rwakeby(n, xi, alpha, beta, gamma, delta)
dghyp(x, lambda, alpha, beta, delta, mu, log = FALSE)
pghyp(q, lambda, alpha, beta, delta, mu, lower.tail = TRUE, log.p = FALSE)
qghyp(p, lambda, alpha, beta, delta, mu, lower.tail = TRUE, log.p = FALSE)
rghyp(n, lambda, alpha, beta, delta, mu)
dtruncnorm(x, mean, sd, a, b, log = FALSE)
ptruncnorm(q, mean, sd, a, b, lower.tail = TRUE, log.p = FALSE)
qtruncnorm(p, mean, sd, a, b, lower.tail = TRUE, log.p = FALSE)
rtruncnorm(n, mean, sd, a, b)
dnakagami(x, m, Omega, log = FALSE)
pnakagami(q, m, Omega, lower.tail = TRUE, log.p = FALSE)
qnakagami(p, m, Omega, lower.tail = TRUE, log.p = FALSE)
rnakagami(n, m, Omega)
Arguments
x, q |
Numeric vector of quantiles. |
p |
Numeric vector of probabilities in |
prob |
Numeric vector of probabilities in |
n |
Integer: number of observations to generate. |
nu |
Degrees of freedom for the Student-t ( |
mu, sigma |
Location and scale parameters. |
b |
Scale parameter for Laplace; also the shape parameter of the
Generalised Gamma (used as the third shape in |
d |
Depth shape parameter of the Generalised Gamma. |
lambda |
Inverse Gaussian shape parameter; Lomax scale parameter;
Johnson SU scale parameter ( |
scale, shape |
Scale and shape parameters. |
shape1, shape2 |
Shape parameters. |
alpha, beta |
Gompertz and Birnbaum-Saunders parameters; Lomax uses |
meanlog |
Mean of the log-transformed variable (log-scale location) for
|
sdlog |
Standard deviation of the log-transformed variable (log-scale
spread, |
thres |
Lower threshold (location shift) for 3-parameter distributions. |
min, max |
Support bounds for the Right Triangular. |
log, log.p |
Logical: if |
lower.tail |
Logical: if |
shape3 |
Third shape parameter for |
xi |
Location parameter for Kappa, Wakeby, and Johnson SU distributions. |
h |
Lower shape parameter for the Kappa four-parameter distribution. |
kappa |
Upper shape parameter for the Kappa four-parameter distribution; also the asymmetry parameter for the Asymmetric Laplace. |
theta |
Rate parameter for the Lindley distribution ( |
gamma |
Shape parameter for the Johnson SU distribution; also a scale parameter in the Wakeby distribution. |
delta |
Shape parameter for the Johnson SU and Wakeby distributions;
also the spread parameter for the NIG and GHyp distributions
( |
m |
Shape parameter for the Nakagami distribution ( |
Omega |
Spread parameter for the Nakagami distribution ( |
mean, sd |
Mean and standard deviation for the Truncated Normal. |
a |
Lower truncation bound for |
Value
A numeric vector of densities, probabilities, quantiles, or random samples,
consistent with the standard R d/p/q/r
convention.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse to fit these distributions to data;
fitverse_distributions for the full distribution catalogue;
dfitverse for evaluating the fitted best-fit distribution.
Examples
## Rayleigh
curve(drayleigh(x, sigma = 2), from = 0, to = 10,
main = "Rayleigh(sigma=2)", ylab = "Density")
## Kumaraswamy (bounded to (0,1))
curve(dkumaraswamy(x, shape1 = 2, shape2 = 5), from = 0, to = 1,
main = "Kumaraswamy(2, 5)", ylab = "Density")
## Birnbaum-Saunders round-trip
p <- c(0.1, 0.5, 0.9)
q <- qbirnbaum_saunders(p, alpha = 0.5, beta = 100)
pbirnbaum_saunders(q, alpha = 0.5, beta = 100) # recovers p
## Inverse Gaussian random samples
set.seed(1)
x <- rinvgaussian(200, mu = 5, lambda = 10)
hist(x, breaks = 20, main = "Inverse Gaussian(5, 10)")
Three-Parameter Weibull Distribution
Description
Density, cumulative distribution function, quantile function, and random
generation for the three-parameter Weibull distribution with shape
\beta > 0, scale \alpha > 0, and threshold (location)
\gamma. The support is x > \gamma.
Usage
dweibull3p(x, shape, scale, thres, log = FALSE)
pweibull3p(q, shape, scale, thres, lower.tail = TRUE, log.p = FALSE)
qweibull3p(p, shape, scale, thres, lower.tail = TRUE, log.p = FALSE)
rweibull3p(n, shape, scale, thres)
Arguments
x, q |
Numeric vector of quantiles. |
p |
Numeric vector of probabilities in |
n |
Integer: number of observations to generate. |
shape |
Positive shape parameter |
scale |
Positive scale parameter |
thres |
Real-valued threshold (location) parameter |
log, log.p |
Logical: if |
lower.tail |
Logical: if |
Details
The three-parameter Weibull is a location-shifted version of the standard
two-parameter Weibull. Let Y = X - \gamma; then Y \sim
\mathrm{Weibull}(\beta, \alpha). The PDF for x > \gamma is
f(x) = \frac{\beta}{\alpha}
\left(\frac{x - \gamma}{\alpha}\right)^{\beta - 1}
\exp\!\left[-\left(\frac{x - \gamma}{\alpha}\right)^{\beta}\right].
Internally these functions shift x by thres and delegate to
dweibull, pweibull,
qweibull, and rweibull.
Value
dweibull3pNumeric vector of density values.
pweibull3pNumeric vector of probabilities.
qweibull3pNumeric vector of quantiles.
rweibull3pNumeric vector of random samples.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
dweibull for the two-parameter Weibull;
fitverse with dists = "weibull3" to fit this
distribution by MLE.
Examples
## PDF and CDF
curve(dweibull3p(x, shape = 2, scale = 10, thres = 5),
from = 5, to = 35, ylab = "Density",
main = "Weibull(2, 10) shifted by 5")
## Quantile / CDF round-trip
p <- c(0.1, 0.5, 0.9)
q <- qweibull3p(p, shape = 2, scale = 10, thres = 5)
pweibull3p(q, shape = 2, scale = 10, thres = 5) # should recover p
## Random samples
set.seed(1)
x <- rweibull3p(200, shape = 1.8, scale = 50, thres = 10)
hist(x, breaks = 20, main = "Weibull(1.8, 50) with threshold 10")
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.
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 ( |
dists |
Character vector of distribution keys to try, or |
method |
Character vector specifying which estimation method(s) to use. One or more of:
When multiple methods are supplied (e.g. |
criterion |
Character: the information criterion used for ranking and best-model
selection. Either 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 |
plot |
Logical: should a diagnostic plot be produced and printed?
Default |
interactive |
Logical: if |
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 |
progress |
Optional function of the form |
verbose |
Logical: print progress messages to the console? Default |
... |
Additional arguments passed to |
Details
Workflow
fitverse() executes the following steps:
-
Validate and clean – removes non-finite values; checks that at least 4 observations remain.
-
Filter distributions – distributions whose support is incompatible with the data (e.g. positive-only Gamma when data contains negative values) are silently excluded.
-
Fit – calls
fit_mle_all(),fit_mom_all(), and/orfit_lmom_all()according tomethod. -
Goodness-of-fit – attaches Kolmogorov-Smirnov (KS), Anderson-Darling (AD), and Cramer-von Mises (CvM) test results to each fit result.
-
Rank – builds a table ordered by
criterion(ascending AIC or BIC). -
Select – chooses the model with the lowest AIC (or BIC).
-
Summarise – computes
compute_data_summary()and stores it in the returned object. -
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 viafitdistrplus::fitdist()with bounded L-BFGS-B optimisation where parameter constraints exist. - MOM
-
Equates the first
ksample moments to their theoretical counterparts and solves for thekparameters. Closed-form solutions are used where available (Normal, Gamma, Log-Normal, Exponential, Beta, Logistic, Uniform, Gumbel, Pareto, Inverse Gamma); numerical solution viastats::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_keyCharacter: distribution key (e.g.
"gamma").methodCharacter: estimation method (
"MLE","MOM", or"LMOM").paramsNamed numeric vector of parameter estimates.
loglikNumeric: maximised log-likelihood.
aicNumeric: Akaike Information Criterion.
bicNumeric: Bayesian Information Criterion.
n_paramsInteger: number of estimated parameters.
nInteger: sample size used.
convergedLogical: did the optimiser converge?
gofData frame of goodness-of-fit test results (Test, Statistic, P_value, Stars), or
NULLif 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). dataNumeric vector: the cleaned input data.
nInteger: number of finite observations used.
xlabCharacter: 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. criterionCharacter:
"AIC"or"BIC".methodCharacter vector: method(s) used.
callThe 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. 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
Fit Distributions to All Columns of a Data Frame
Description
Applies fitverse() to every numeric column of a data frame
(or matrix, or named list), collects the results, and returns a tidy
summary table alongside the full list of fitted objects.
Use fitverse_batch() for automated data characterisation workflows,
survey-population profiling, or as a pre-processing step before optimal
stratification with stratifyR.
Usage
fitverse_batch(data,
cols = NULL,
dists = "all",
method = "MLE",
criterion = "AIC",
top_n = 3L,
plot = FALSE,
progress = NULL,
verbose = TRUE)
## S3 method for class 'fitverse_batch'
print(x, ...)
## S3 method for class 'fitverse_batch'
summary(object, ...)
Arguments
data |
A |
cols |
Character vector of column names to process. If |
dists |
Distribution keys to try, or |
method |
Estimation method(s): |
criterion |
|
top_n |
Integer: number of top-ranked distributions stored in each fit.
Default |
plot |
Logical: produce and print a diagnostic plot for each variable?
Default |
progress |
Optional callback |
verbose |
Logical: print per-column progress messages? Default |
x, object |
An object of class |
... |
Currently unused. |
Details
fitverse_batch() iterates over columns with a tryCatch()
wrapper so that a fitting failure for one column does not abort the
entire batch. Failed columns are collected in the failed element
of the returned object.
Column names containing spaces or special characters are handled correctly
via make.names() internally.
Value
An S3 object of class "fitverse_batch" with elements:
fits-
Named list of
"fitverse"objects, one per successfully fitted column. summary-
Data frame with one row per column, columns:
variable,n,best_dist,method,AIC,BIC,loglik,KS_p,AD_p. failed-
Character vector of column names for which fitting failed, or
character(0)if all succeeded. criterionCharacter: the criterion used.
callThe matched call.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse for single-column fitting.
generate_report for producing a report from batch results.
Examples
# Fit all numeric columns of the airquality dataset
data(airquality)
batch <- fitverse_batch(airquality,
method = "MLE",
verbose = FALSE)
print(batch)
summary(batch)
# Access the fit for the Ozone column
batch$fits[["Ozone"]]
Fit Parametric Distributions to Censored or Truncated Data
Description
Estimates distribution parameters by maximising the censored log-likelihood for data that may be right-censored, left-censored, interval-censored, and/or left-/right-truncated, or any combination of these. Seven distribution families are supported. Fits are ranked by AIC or BIC, and a nonparametric Kaplan–Meier estimate is overlaid automatically on the survival or CDF plot.
Usage
fitverse_censored(x,
status = NULL,
x_upper = NULL,
trunc_lower = -Inf,
trunc_upper = Inf,
dists = c("normal", "lognormal", "weibull",
"exponential", "gamma",
"loglogistic", "gumbel"),
criterion = c("AIC", "BIC"),
n_starts = 3L,
xlab = "x",
draw = TRUE)
## S3 method for class 'fitverse_censored'
print(x, ...)
## S3 method for class 'fitverse_censored'
plot(x, top_n = 3L, ...)
Arguments
x |
Numeric vector of observed or censored values. For right-censored
observations this is the last observed time; for left-censored
observations it is the detection-limit value; for interval-censored
observations it is the lower bound of the interval.
In |
status |
Integer vector of the same length as
If |
x_upper |
Numeric vector of upper bounds for interval-censored observations
( |
trunc_lower |
Numeric scalar: left (lower) truncation bound. Observations below this
value are never recorded; the likelihood is normalised by
|
trunc_upper |
Numeric scalar: right (upper) truncation bound. Default |
dists |
Character vector of distribution keys to fit. Any subset of
|
criterion |
Character: |
n_starts |
Positive integer: number of random starting points per distribution.
Increasing this reduces the risk of the optimiser converging to a local
optimum. Default |
xlab |
Character: variable label used in plot axis titles. Default |
draw |
Logical: produce a survival-function (right-censored) or
cumulative-distribution (otherwise) plot? Default |
top_n |
Positive integer: number of top-ranked distributions to overlay on the
plot. Default |
... |
Further arguments passed to or from other methods. |
Value
An object of class "fitverse_censored", which is a named list with
the following elements:
fits-
List of fit objects ordered by
criterion(best first). Each element is a list with:dist_key(character),display(character display name),par(named numeric vector of parameter estimates),log_lik(numeric),aic(numeric),bic(numeric),n_par(integer),converged(logical). rankings-
Data frame with columns
Rank,Distribution,LogLik,AIC,BIC,Converged, sorted bycriterion. x,status,x_upper-
Cleaned copies of the input data vectors (non-finite values removed).
trunc_lower,trunc_upperTruncation bounds as supplied.
xlabVariable label.
criterionRanking criterion used (
"AIC"or"BIC").
References
Meeker, W. Q. and Escobar, L. A. (1998). Statistical Methods for Reliability Data. Wiley, New York.
Lawless, J. F. (2003). Statistical Models and Methods for Lifetime Data, 2nd ed. Wiley, Hoboken.
Kaplan, E. L. and Meier, P. (1958). Nonparametric estimation from incomplete observations. Journal of the American Statistical Association, 53(282), 457–481. doi:10.1080/01621459.1958.10501452
See Also
fitverse for uncensored data fitting;
fitverse_distributions for the full distribution library.
Examples
## Right-censored survival data (Weibull true model)
set.seed(1)
times <- rweibull(100, shape = 1.8, scale = 50)
censor <- rexp(100, rate = 1/60)
x <- pmin(times, censor)
status <- as.integer(times <= censor) # 1 = event, 0 = right-censored
fit_s <- fitverse_censored(x, status,
dists = c("weibull", "lognormal", "gamma"),
xlab = "Survival time (hours)")
print(fit_s)
plot(fit_s, top_n = 3)
## Left-censored environmental data (below detection limit)
set.seed(2)
conc <- rlnorm(80, meanlog = 1.5, sdlog = 0.7)
dl <- 3.0
x_env <- ifelse(conc >= dl, conc, dl)
status_env <- ifelse(conc >= dl, 1L, 2L)
fit_e <- fitverse_censored(x_env, status_env,
dists = c("lognormal", "gamma"),
xlab = "Concentration (mg/L)")
fit_e$rankings
## Left-truncated occupational exposure data
set.seed(3)
exposure <- rlnorm(300, meanlog = 2.5, sdlog = 0.5)
exposure <- exposure[exposure > 5] # only workers above LOQ recorded
fit_t <- fitverse_censored(exposure, trunc_lower = 5,
dists = c("lognormal", "gamma", "weibull"),
xlab = "Exposure (mg/m3)")
fit_t$fits[[1L]]$par
List All Distributions Supported by FitVerse
Description
Returns a data frame describing all 52 probability distributions that FitVerse can fit, including their distribution keys, full names, number of parameters, support, available estimation methods, and the underlying R function source.
This page also documents the mathematical details of the four hydrological / extreme-value distributions: Generalised Pareto (GPD), Pearson Type III (P3), Log-Pearson Type III (LP3), and Generalised Logistic (GLO).
Usage
fitverse_distributions(method = NULL)
Arguments
method |
Optional character scalar: filter to distributions available for a
specific estimation method. One of |
Details
Complete distribution table (52 families)
| Key | Distribution | Params | Support | Family |
normal | Normal | 2 | (-\infty,\infty) | Symmetric |
logistic | Logistic | 2 | (-\infty,\infty) | Symmetric |
cauchy | Cauchy | 2 | (-\infty,\infty) | Symmetric |
laplace | Laplace | 2 | (-\infty,\infty) | Symmetric |
student_t | Student-t (location-scale) | 3 | (-\infty,\infty) | Symmetric |
truncnorm | Truncated Normal | 4 | [a,b] | Symmetric |
skewnormal | Skew-Normal | 3 | (-\infty,\infty) | Asymmetric |
gnorm | Generalised Normal | 3 | (-\infty,\infty) | Asymmetric |
alaplace | Asymmetric Laplace | 3 | (-\infty,\infty) | Asymmetric |
johnsonsu | Johnson SU | 4 | (-\infty,\infty) | Asymmetric |
gamma | Gamma | 2 | (0,\infty) | Right-skewed |
gamma3 | Gamma (3-parameter) | 3 | (\mu,\infty) | Right-skewed |
lognormal | Log-Normal | 2 | (0,\infty) | Right-skewed |
lnorm3 | Log-Normal (3-parameter) | 3 | (\mu,\infty) | Right-skewed |
exponential | Exponential | 1 | (0,\infty) | Right-skewed |
expexp | Exponentiated Exponential | 2 | (0,\infty) | Right-skewed |
weibull | Weibull (2-parameter) | 2 | (0,\infty) | Right-skewed |
weibull3p | Weibull (3-parameter) | 3 | (\mu,\infty) | Right-skewed |
expweibull | Exponentiated Weibull | 3 | (0,\infty) | Right-skewed |
loglogistic | Log-Logistic | 2 | (0,\infty) | Right-skewed |
invgaussian | Inverse Gaussian | 2 | (0,\infty) | Right-skewed |
invgamma | Inverse Gamma | 2 | (0,\infty) | Right-skewed |
invweibull | Inverse Weibull | 2 | (0,\infty) | Right-skewed |
gompertz | Gompertz | 2 | (0,\infty) | Right-skewed |
birnbaum_saunders | Birnbaum-Saunders | 2 | (0,\infty) | Right-skewed |
rayleigh | Rayleigh | 1 | (0,\infty) | Right-skewed |
halfnormal | Half-Normal | 1 | (0,\infty) | Right-skewed |
lindley | Lindley | 1 | (0,\infty) | Right-skewed |
nakagami | Nakagami | 2 | (0,\infty) | Right-skewed |
gengamma | Generalised Gamma | 3 | (0,\infty) | Right-skewed |
pareto | Pareto | 2 | (x_m,\infty) | Heavy-tailed |
burr | Burr XII | 3 | (0,\infty) | Heavy-tailed |
lomax | Lomax (Pareto Type II) | 2 | (0,\infty) | Heavy-tailed |
paralogistic | Paralogistic | 2 | (0,\infty) | Heavy-tailed |
dagum | Dagum | 3 | (0,\infty) | Heavy-tailed |
gb2 | GB2 (Generalised Beta II) | 4 | (0,\infty) | Heavy-tailed |
nig | Normal Inverse Gaussian | 4 | (-\infty,\infty) | Heavy-tailed |
ghyp | Generalised Hyperbolic | 5 | (-\infty,\infty) | Heavy-tailed |
gev | Generalised Extreme Value | 3 | depends on shape | Extreme-value |
gumbel | Gumbel (Type I EV) | 2 | (-\infty,\infty) | Extreme-value |
gpd | Generalised Pareto | 3 | [\mu,\infty) or bdd | Extreme-value |
glo | Generalised Logistic | 3 | depends on shape | Extreme-value |
pearson3 | Pearson Type III | 3 | (-\infty,\infty) | Extreme-value |
lpearson3 | Log-Pearson Type III | 3 | (0,\infty) | Extreme-value |
kap4 | Kappa-4 | 4 | depends on shape | Extreme-value |
wakeby | Wakeby | 5 | (0,\infty) | Extreme-value |
beta | Beta | 2 | (0,1) | Bounded |
uniform | Uniform | 2 | [a,b] | Bounded |
triangular | Triangular | 3 | [a,b] | Bounded |
rtriangle | Right Triangular | 2 | [a,b] | Bounded |
pert | PERT (Beta-PERT) | 3 | [a,b] | Bounded |
kumaraswamy | Kumaraswamy | 2 | (0,1) | Bounded |
Hydrological and extreme-value distributions (v1.0 additions)
The four distributions below – GPD, Pearson III, Log-Pearson III, and
GLO – are central to flood-frequency analysis and Peaks-Over-Threshold
modelling. They share a common implementation strategy: closed-form
d/p/q/r functions are registered in the internal
.FITVERSE_DPQR_OVERRIDES table, bypassing any external package
dependency and guaranteeing consistent behaviour across platforms.
Generalised Pareto Distribution (GPD) – key: "gpd"
Parameters: \mu (location / threshold), \sigma > 0
(scale), \xi (shape).
PDF (\xi \neq 0):
f(x\,;\,\mu,\sigma,\xi)=\frac{1}{\sigma}
\Bigl(1+\xi\,\frac{x-\mu}{\sigma}\Bigr)^{-1/\xi-1}
Support: x \ge \mu when \xi \ge 0;
\mu \le x \le \mu - \sigma/\xi when \xi < 0.
Reduces to \mathrm{Exp}(1/\sigma) when \xi = 0.
Quantile function:
Q(p)=\mu+\frac{\sigma}{\xi}\bigl[(1-p)^{-\xi}-1\bigr],\quad\xi\neq 0
\qquad Q(p)=\mu-\sigma\log(1-p),\quad\xi=0
Method of Moments: Fix \hat\mu=\min(x)-\varepsilon;
let y_i=x_i-\hat\mu. Then
\hat\xi=(1-\bar y^2/s_y^2)/2,
\hat\sigma=\bar y(1-\hat\xi).
Valid only when \hat\xi<1/2.
L-Moments: via lmomco::pargpa().
Sign convention: FitVerse \xi=-\kappa_{\text{lmomco}}.
Use case: Peaks-Over-Threshold analysis; insurance excess-of-loss modelling (Pickands, 1975).
Pearson Type III (P3) – key: "pearson3"
Parameters: \alpha>0 (shape), \beta (scale; may be
negative), \zeta (location).
Relationship to Gamma:
X\sim\mathrm{P3}(\alpha,\beta,\zeta)
\;\Leftrightarrow\;
(X-\zeta)/\beta\sim\mathrm{Gamma}(\alpha,\,\mathrm{rate}=1)
PDF:
f(x\,;\,\alpha,\beta,\zeta)=
\frac{|\beta|^{-1}}{\Gamma(\alpha)}
\Bigl(\frac{x-\zeta}{\beta}\Bigr)^{\!\alpha-1}
\exp\!\Bigl(-\frac{x-\zeta}{\beta}\Bigr),
\quad\frac{x-\zeta}{\beta}>0
Positive \beta gives right-skewed; negative \beta gives
left-skewed data.
Method of Moments: Let \bar x,s,g be the sample mean,
standard deviation, and skewness coefficient. Then:
\hat\alpha=4/g^2,\qquad\hat\beta=sg/2,\qquad\hat\zeta=\bar x-2s/g
L-Moments: via lmomco::parpe3(), which returns
(\mu,\sigma,\gamma). FitVerse converts using the MOM formulae above.
Use case: Annual peak-flow frequency analysis (US Bulletin 17C; England et al., 2019); meteorological extremes.
Log-Pearson Type III (LP3) – key: "lpearson3"
Parameters: \alpha>0 (shape), \beta (scale),
\zeta (location) – all defined in log-space.
X\sim\mathrm{LP3}(\alpha,\beta,\zeta)
\;\Leftrightarrow\;
\log X\sim\mathrm{P3}(\alpha,\beta,\zeta)
PDF:
f(x\,;\,\alpha,\beta,\zeta)
=\frac{f_{\mathrm{P3}}(\log x\,;\,\alpha,\beta,\zeta)}{x},\quad x>0
CDF and quantile:
F(x)=F_{\mathrm{P3}}(\log x),\qquad Q(p)=\exp\bigl[Q_{\mathrm{P3}}(p)\bigr]
Method of Moments and L-Moments: Pearson III estimators applied
to \log x_i. L-Moments use lmomco::parpe3() on the
log-transformed sample.
Use case: The US federal standard for flood-frequency estimation (Bulletin 17C; England et al., 2019).
Generalised Logistic Distribution (GLO) – key: "glo"
Parameters: \xi (location), \alpha>0 (scale),
\kappa (shape).
CDF (\kappa\neq 0):
F(x\,;\,\xi,\alpha,\kappa)
=\frac{1}{1+\bigl[1-\kappa(x-\xi)/\alpha\bigr]^{1/\kappa}}
Reduces to \mathrm{Logistic}(\xi,\alpha) when \kappa=0.
Quantile function:
Q(p)=\xi+\frac{\alpha}{\kappa}\Bigl[1-\Bigl(\frac{1-p}{p}\Bigr)^{\!\kappa}\Bigr],
\quad\kappa\neq 0
\qquad Q(p)=\xi+\alpha\log\frac{p}{1-p},\quad\kappa=0
Support: (-\infty,\,\xi+\alpha/\kappa) for \kappa>0;
(\xi+\alpha/\kappa,\,\infty) for \kappa<0;
all real for \kappa=0.
L-Moments: via lmomco::parglo().
No sign flip: FitVerse \kappa=\kappa_{\text{lmomco}}.
MOM is not implemented for GLO (complex moment system; use LMOM or MLE).
Use case: The recommended flood-frequency distribution in the United Kingdom (WINFAP; Robson & Reed, 1999).
L-moment shape-parameter sign conventions
lmomco uses the opposite sign for the shape parameter of GEV and GPD:
| Distribution | lmomco \kappa | FitVerse shape |
| GEV | \kappa |
-\kappa (sign flip) |
| GPD | \kappa |
-\kappa (sign flip) |
| GLO | \kappa |
\kappa (no flip)
|
Value
A data frame with one row per distribution and columns:
- Key
Character: the string to pass in the
distsargument offitverse()and related functions.- Name
Full distribution name.
- Family
Broad family tag (e.g.
"Extreme-value","Right-skewed").- Package
The R package supplying
d/p/q/rfunctions, orNAfor distributions with FitVerse-internal implementations.- MLE
Character
"Yes"or"-": MLE available?- MOM
Character
"Yes"or"-": MOM available?- LMOM
Character
"Yes"or"-": L-Moments available?
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
References
England, J. F., Jr., et al. (2019). Guidelines for Determining Flood Flow Frequency – Bulletin 17C. USGS Techniques and Methods, Book 4, Chapter B5.
Hosking, J. R. M. and Wallis, J. R. (1997). Regional Frequency Analysis: An Approach Based on L-moments. Cambridge University Press.
Pickands, J. (1975). Statistical inference using extreme order statistics. The Annals of Statistics, 3(1), 119–131.
Robson, A. and Reed, D. (1999). Flood Estimation Handbook, Volume 3. Institute of Hydrology, Wallingford, UK.
See Also
fitverse for fitting any of the 52 distributions.
compare_dists for quick multi-distribution screening.
return_level for T-year return levels.
bootstrap_ci for parametric bootstrap confidence intervals.
Examples
# All 52 distributions
fitverse_distributions()
# Only those with L-moment support
fitverse_distributions(method = "LMOM")
# Extreme-value / hydrological families
ev <- fitverse_distributions()
ev[ev$Key %in% c("gev","gumbel","gpd","pearson3","lpearson3","glo"), ]
## ---- GPD (Peaks-Over-Threshold) ----------------------------------------
set.seed(42)
x_excess <- evd::rgpd(300, loc = 0, scale = 2, shape = 0.1)
fit_gpd <- fitverse(x_excess, dists = "gpd", method = "LMOM",
plot = FALSE, verbose = FALSE)
coef(fit_gpd)
return_level(fit_gpd, return_periods = c(10, 50, 100))
## ---- Pearson III (Bulletin 17C style) ----------------------------------
## Pearson III with shape=5, scale=3, loc=10 is equivalent to
## a shifted Gamma: X = loc + Gamma(shape, scale)
set.seed(42)
x_p3 <- rgamma(200, shape = 5, scale = 3) + 10
fit_p3 <- fitverse(x_p3, dists = "pearson3", method = "LMOM",
plot = FALSE, verbose = FALSE)
coef(fit_p3)
## ---- Log-Pearson III ----------------------------------------------------
## Log-Pearson III: log(X) ~ Pearson III(shape, scale, loc)
## so X = exp(loc + Gamma(shape, scale))
set.seed(42)
x_lp3 <- exp(rgamma(200, shape = 5, scale = 0.4) + 2)
fit_lp3 <- fitverse(x_lp3, dists = "lpearson3", method = "LMOM",
plot = FALSE, verbose = FALSE)
coef(fit_lp3)
## ---- GLO (UK WINFAP style) ----------------------------------------------
## Generate GLO samples via the lmomco quantile function
set.seed(42)
x_glo <- lmomco::qlmomco(runif(200),
lmomco::vec2par(c(50, 8, 0.12), type = "glo"))
fit_glo <- fitverse(x_glo, dists = "glo", method = "LMOM",
plot = FALSE, verbose = FALSE)
coef(fit_glo)
return_level(fit_glo, return_periods = c(2, 10, 50, 100, 200))
Fit Distributions to Grouped or Interval-Censored Data
Description
fitverse_grouped() fits one or more parametric distributions to
data that are available only in grouped (frequency-table) or
interval-censored form. It accepts either class midpoints with counts, or
explicit lower and upper interval boundaries with counts.
read_grouped_csv() reads a two- or three-column CSV file into the
format expected by fitverse_grouped().
Usage
fitverse_grouped(midpoints = NULL,
counts,
lower = NULL,
upper = NULL,
dists = "auto",
method = "All",
xlab = "x",
top_n = 5L,
verbose = FALSE)
read_grouped_csv(file, sep = ",")
Arguments
midpoints |
Numeric vector of class midpoints (one per class).
Supply either |
counts |
Integer vector of observed frequencies for each class.
Must be the same length as |
lower |
Numeric vector of lower interval boundaries. Required when
|
upper |
Numeric vector of upper interval boundaries. Required when
|
dists |
Character vector of distribution names to fit, or
|
method |
Fitting method: |
xlab |
Character label for the data axis used in output summaries.
Default |
top_n |
Integer: number of top-ranked distributions to include in
the printed summary. Default |
verbose |
Logical: print per-distribution fitting progress?
Default |
file |
Path to a CSV file. The file may contain comment lines
beginning with |
sep |
Column separator for |
Details
Input formats
fitverse_grouped() accepts two input formats.
Midpoint format: Supply midpoints and counts.
Interval boundaries are reconstructed by assuming equal-width classes.
Boundary format: Supply lower, upper, and
counts. Classes need not be equal-width. Open-ended classes
(e.g., an upper bound of Inf) are handled by replacing the
infinite bound with a large finite value for midpoint computation.
Estimation
For each candidate distribution, parameters are estimated by maximising the interval-censored log-likelihood
\ell(\theta) = \sum_{j} n_j \log\bigl[F(u_j;\theta) - F(l_j;\theta)\bigr]
where n_j is the count in class j, and l_j, u_j
are its lower and upper boundaries.
CSV format for read_grouped_csv()
The CSV file should have either two columns (midpoint, count) or three
columns (lower, upper, count). Column names are detected automatically
from a set of common variants (mid, midpoint, lower,
upper, etc.). Lines starting with # are treated as comments
and ignored.
Value
fitverse_grouped() returns an object of class
"fitverse_grouped" containing:
resultsA data frame of fitted distributions ranked by AIC, with columns for distribution name, AIC, BIC, log-likelihood, estimated parameters, and goodness-of-fit statistics.
bestThe name of the best-fitting distribution.
dataA list with elements
midpoints,counts,lower, andupper.callThe matched call.
read_grouped_csv() returns a named list with elements
midpoints and counts (midpoint format) or lower,
upper, and counts (boundary format), ready to be passed
directly to fitverse_grouped().
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse for fitting to individual (ungrouped) data.
fitverse_distributions for the full distribution catalogue.
Examples
## Midpoint format
mid <- c(5, 15, 25, 35, 45, 55, 65, 75)
count <- c(3, 12, 25, 30, 18, 8, 3, 1)
fit <- fitverse_grouped(midpoints = mid, counts = count,
method = "MLE", verbose = FALSE)
print(fit)
## Boundary format
low <- c(0, 10, 20, 30, 40, 50, 60, 70)
high <- c(10, 20, 30, 40, 50, 60, 70, 80)
fit2 <- fitverse_grouped(lower = low, upper = high, counts = count,
method = "MLE", verbose = FALSE)
print(fit2)
## Reading from CSV
## A file with columns: lower, upper, count
tmp <- tempfile(fileext = ".csv")
writeLines(c(
"# Example grouped data",
"lower,upper,count",
"0,10,5",
"10,20,18",
"20,30,30",
"30,40,25",
"40,50,12",
"50,60,4"
), tmp)
dat <- read_grouped_csv(tmp)
fit3 <- fitverse_grouped(lower = dat$lower, upper = dat$upper,
counts = dat$counts)
print(fit3)
S3 Methods for fitverse Objects
Description
Standard S3 methods for objects of class "fitverse" as returned by
fitverse(). These methods provide a consistent interface
for extracting, displaying, and serialising fitted distribution results.
Usage
## S3 method for class 'fitverse'
print(x, ...)
## S3 method for class 'fitverse'
summary(object, top_n = 10L, ...)
## S3 method for class 'fitverse'
coef(object, ...)
## S3 method for class 'fitverse'
logLik(object, ...)
## S3 method for class 'fitverse'
AIC(object, ..., k = 2)
## S3 method for class 'fitverse'
BIC(object, ...)
## S3 method for class 'fitverse'
as.list(x, ...)
Arguments
x, object |
An object of class |
top_n |
Integer: number of top-ranked distributions to show in the ranking
table printed by |
k |
Numeric: penalty per parameter used by |
... |
Currently unused. |
Details
print.fitverse()-
Prints a concise single-screen summary: best-fit distribution, estimation method, number of parameters, parameter estimates, log-likelihood, AIC, BIC, and up to three goodness-of-fit test results.
summary.fitverse()-
Prints the data summary (from
compute_data_summary()), the fulltop_nranking table, and the GoF test results for the best-fit model. coef.fitverse()-
Returns the named numeric vector of parameter estimates for the best-fit model. For example,
c(shape = 2.14, rate = 0.43)for a Gamma fit. logLik.fitverse()-
Returns an object of class
"logLik"with the maximised log-likelihood and the degrees of freedom (number of parameters). Compatible withstats::AIC()andstats::BIC(). AIC.fitverse()-
Returns the Akaike Information Criterion
\mathrm{AIC} = -2\ell + k \cdot p, where\ellis the log-likelihood,pis the number of parameters, andkis the penalty (default 2). BIC.fitverse()-
Returns the Bayesian Information Criterion
\mathrm{BIC} = -2\ell + p \log n. as.list.fitverse()-
Converts the
fitverseobject to a plain list suitable for JSON serialisation (used byto_json()). Non-serialisable internals (raw fit objects, closures) are stripped. Returns:best_fit(dist_key, method, params, loglik, aic, bic),ranking,data_summary,n,xlab,criterion.
Value
print.fitverse()Invisibly returns
x.summary.fitverse()Invisibly returns
object.coef.fitverse()Named numeric vector of parameter estimates.
logLik.fitverse()Object of class
"logLik".AIC.fitverse()Numeric scalar.
BIC.fitverse()Numeric scalar.
as.list.fitverse()A named list safe for JSON serialisation.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse, to_json, plot.fitverse.
Examples
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
fit <- fitverse(x, plot = FALSE, verbose = FALSE)
print(fit)
coef(fit)
logLik(fit)
AIC(fit)
BIC(fit)
# Serialisation-ready list
lst <- as.list(fit)
names(lst)
Generate an HTML or PDF Report for a Fitted Distribution
Description
Produces a standalone, self-contained HTML (or PDF) report that documents the fitted distribution, estimated parameters, goodness-of-fit tests, descriptive statistics, diagnostic plots, and (optionally) bootstrap confidence intervals.
If rmarkdown is installed, the report is rendered from an R Markdown template. Otherwise, a pure HTML fallback is used with the diagnostic plot embedded as a base64-encoded PNG image.
Usage
generate_report(fit,
output_file = NULL,
title = "FitVerse: Distribution Fitting Report",
author = "",
boot = NULL,
top_n = 5L,
open = TRUE)
Arguments
fit |
An object of class |
output_file |
Character: path to the output file. If |
title |
Character: report title. Defaults to
|
author |
Character: author name to include in the report header.
Default |
boot |
An object of class |
top_n |
Integer: number of distributions to show in the ranking table.
Default |
open |
Logical: open the report in the system's default browser after
writing? Default |
Details
R Markdown path (recommended)
When rmarkdown is available, generate_report() writes a
temporary .Rmd file and calls rmarkdown::render() to produce
a self-contained HTML document using the html_document format with
self_contained = TRUE. The fitted object is passed via a temporary
.rds file to avoid workspace pollution.
HTML fallback path
When rmarkdown is unavailable, a self-contained HTML file is built in pure R:
The diagnostic plot is saved to a temporary PNG and encoded as a base64 data URI using base64enc (if available) or a manual hex-to-base64 conversion.
Tables are rendered as HTML
<table>elements.The output is a single-file HTML document with embedded CSS.
Value
Invisibly returns the normalised path to the output file (character).
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
bootstrap_ci for confidence intervals to include in the
report.
save_plot to save the diagnostic plot separately.
Examples
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
fit <- fitverse(x, xlab = "Waiting time (s)", plot = FALSE, verbose = FALSE)
# Write report to a temporary directory so no files are left in the working dir
path <- generate_report(fit,
title = "Gamma Fit Example",
author = "Karuna Reddy",
output_file = file.path(tempdir(), "fitverse_report.html"),
open = FALSE)
message("Report saved to: ", path)
Retrieve a Distribution Registry Entry
Description
Look up a single distribution entry from the FitVerse distribution
registry by its key. This function is primarily intended for use by the
FitVerseApp Shiny application, which needs to access display
names, parameter labels, and PDF equation strings at runtime.
Usage
get_dist_entry(dist_key)
Arguments
dist_key |
Character: the distribution key (e.g., |
Value
A named list containing the registry fields for the requested
distribution (display name, parameter names, support type, method
availability flags, etc.). Raises an error if dist_key is not
found in the registry.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
fitverse_distributions for a tabular view of all registered
distributions and their supported methods.
Examples
e <- get_dist_entry("weibull")
e$display_name # "Weibull (2-Parameter)"
e$supports_lmom # TRUE
L-Moment Ratio Diagram and Extreme-Value Threshold Selection
Description
Two diagnostic tools for exploratory data analysis in FitVerse.
lmrd() produces an L-moment ratio diagram plotting the sample
(\tau_3, \tau_4) pair against the theoretical curves of major
distribution families (GLO, GEV, GNO, PE3, GPA) and their known special
cases (Normal, Logistic, Gumbel, Exponential, Uniform). The diagram
guides distributional identification before formal model fitting.
ev_threshold() plots three threshold-stability diagnostics for
Peaks-Over-Threshold (POT) extreme-value analysis: the Mean Residual Life
(MRL) plot, the shape-stability plot, and the modified-scale-stability
plot. These are used to identify the lowest threshold above which the
Generalised Pareto Distribution (GPD) is a valid model for exceedances.
Usage
lmrd(x = NULL,
xlab = NULL,
distributions = c("glo", "gev", "gno", "pe3", "gpa"),
show_ref_points = TRUE,
draw = TRUE)
ev_threshold(x,
thresholds = NULL,
n_thresholds = 40L,
min_exceedances = 10L,
conf = 0.95,
xlab = "x",
draw = TRUE)
Arguments
x |
Numeric vector of observations. For |
xlab |
Character: x-axis label used in plots. Defaults to
|
distributions |
Character vector: distribution families whose theoretical L-moment ratio curves are drawn. Default covers GLO, GEV, GNO, PE3, and GPA. |
show_ref_points |
Logical: whether to plot the known special-case
reference points (Normal, Logistic, Gumbel, Exponential, Uniform).
Default |
draw |
Logical: if |
thresholds |
Optional numeric vector of candidate threshold values.
If |
n_thresholds |
Integer: number of candidate threshold values to
evaluate when |
min_exceedances |
Integer: minimum number of exceedances required at
each threshold. Thresholds with fewer exceedances are excluded.
Default |
conf |
Numeric in |
Details
lmrd() computes the sample L-skewness \hat\tau_3 and
L-kurtosis \hat\tau_4 via lmoms and plots
the sample point against the theoretical loci for the GLO, GEV, GPA,
GNO, and PE3 families. Exact closed-form curves are used for GLO, GEV,
and GPA (Hosking, 1990); polynomial approximations are used for GNO and
PE3 (Hosking and Wallis, 1997).
ev_threshold() fits a GPD to exceedances at each candidate
threshold u and extracts the estimated shape \hat\xi and
modified scale \hat\sigma^* = \hat\sigma - \hat\xi u. A stable
region in both plots, combined with approximate linearity of the MRL
plot, indicates a suitable threshold.
Value
Both functions return a ggplot object invisibly and (by default)
display the plot.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
References
Hosking, J. R. M. (1990). L-moments: Analysis and estimation of distributions using linear combinations of order statistics. Journal of the Royal Statistical Society B, 52(1), 105–124. doi:10.1111/j.2517-6161.1990.tb01775.x
Hosking, J. R. M. and Wallis, J. R. (1997). Regional Frequency Analysis: An Approach Based on L-Moments. Cambridge University Press.
Davison, A. C. and Smith, R. L. (1990). Models for exceedances over high thresholds. Journal of the Royal Statistical Society B, 52(3), 393–442.
See Also
fitverse with dists = "gpd" for formal GPD fitting
after threshold selection.
Examples
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
lmrd(x, xlab = "Simulated Gamma data")
set.seed(1)
x_ev <- rexp(500, rate = 0.1)
ev_threshold(x_ev, n_thresholds = 30, xlab = "Simulated exponential")
Diagnostic Plot for a fitverse Object
Description
Produces a two-panel diagnostic figure for a fitted fitverse object:
A histogram of the data overlaid with the fitted density curves for the top-ranked distributions. The PDF formula is annotated directly on the figure.
A Q-Q plot of the empirical quantiles against theoretical quantiles from the best-fit distribution.
Either or both panels can be requested. The plot can optionally be returned as an interactive plotly HTML widget.
Usage
## S3 method for class 'fitverse'
plot(x,
which = "both",
top_n = 3L,
xlab = NULL,
interactive = FALSE,
draw = TRUE,
...)
Arguments
x |
An object of class |
which |
Character scalar controlling which panels to draw. One of:
|
top_n |
Integer: number of top-ranked models to overlay on the density panel.
The best-fit model is drawn as a solid line; others as dashed lines
with distinct colours. Default |
xlab |
Character: x-axis label. If |
interactive |
Logical: if |
draw |
Logical: if |
... |
Currently unused; reserved for future extensions. |
Details
The density panel uses ggplot2::geom_histogram(aes(y = after_stat(density)))
with Freedman-Diaconis binning, overlaid with geom_line() curves
evaluated on a fine grid of 512 points spanning the observed data range.
The Q-Q panel compares theoretical quantiles from the best-fit distribution
(evaluated via qfitverse()) against the empirical quantiles of
the data, with a 45-degree reference line.
When which = "both", the two ggplot2 objects are arranged side-by-side
using gridExtra::grid.arrange(). When interactive = TRUE and
which != "both", a single panel is converted with
plotly::ggplotly().
Value
Invisibly returns the plot object(s):
A single ggplot2 object when
whichis"density"or"qq".A
grob(arranged grid object) whenwhich = "both".A plotly widget when
interactive = TRUE.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
save_plot to write the figure to a PNG or PDF file.
fitverse which calls this function automatically when plot = TRUE.
Examples
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
fit <- fitverse(x, plot = FALSE, verbose = FALSE)
# Both panels (default)
plot(fit)
# Density panel only with custom x-axis label
plot(fit, which = "density", xlab = "Value", top_n = 5)
# Q-Q plot only
plot(fit, which = "qq")
Compute T-Year Return Levels from a Fitted Distribution
Description
Computes return levels (quantiles) corresponding to specified return periods
from the best-fit distribution in a fitverse object. Return levels
are widely used in hydrology, climatology, and actuarial science to
characterise the magnitude of rare events.
Usage
return_level(fit,
return_periods = c(2, 5, 10, 20, 50, 100, 200, 500))
Arguments
fit |
An object of class |
return_periods |
Numeric vector of return periods (in years, or whichever time unit the
data represent). Must be |
Details
A T-year return level x_T is the value that is exceeded on average
once every T years (or time units), i.e.:
P(X > x_T) = \frac{1}{T}
x_T = F^{-1}\!\left(1 - \frac{1}{T}\right)
where F^{-1} is the quantile function of the fitted distribution.
Quantiles are computed using qfitverse(), which resolves
the quantile function from the internal distribution registry.
Value
A data frame with one row per return period and columns:
TNumeric: the return period.
exceedance_probNumeric:
1/T, the annual exceedance probability.return_levelNumeric: the estimated T-year return level (upper
1/Tquantile of the fitted distribution).
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
References
Coles, S. (2001). An Introduction to Statistical Modeling of Extreme Values. Springer, London.
Katz, R. W., Parlange, M. B. and Naveau, P. (2002). Statistics of extremes in hydrology. Advances in Water Resources, 25(8-12), 1287–1304.
See Also
qfitverse for quantiles at arbitrary probabilities.
bootstrap_ci for confidence intervals on return levels.
Examples
# Flood frequency analysis with GEV distribution
set.seed(10)
floods <- evd::rgev(80, loc = 200, scale = 40, shape = 0.15)
fit <- fitverse(floods,
dists = c("gev", "gumbel", "lognormal"),
method = "MLE",
xlab = "Annual maximum flood (m3/s)",
plot = FALSE,
verbose = FALSE)
rl <- return_level(fit)
print(rl)
# 100-year return level
rl[rl$T == 100, "return_level"]
Save a FitVerse Diagnostic Plot to File
Description
Renders the two-panel diagnostic plot for a fitverse object and
saves it as a high-resolution PNG (or PDF) file, without displaying the
figure on the current graphics device. Suitable for embedding in reports
or automated pipelines.
Usage
save_plot(fit,
file = file.path(tempdir(), "fitverse_plot.png"),
which = "both",
top_n = 3L,
xlab = NULL,
width = 14,
height = 5.5,
dpi = 600,
...)
Arguments
fit |
An object of class |
file |
Character: output file path. The file extension determines the format:
|
which |
Which panels to save: |
top_n |
Number of top-ranked distributions to show on the density panel.
Default |
xlab |
Character: x-axis label. Defaults to |
width |
Numeric: plot width in inches. Default |
height |
Numeric: plot height in inches. Default |
dpi |
Integer: resolution in dots per inch. Default |
... |
Additional arguments passed to |
Details
Uses grDevices::png() (or grDevices::pdf() / grDevices::svg()
depending on file extension) and gridExtra::grid.arrange() to render
both panels in a single device call, ensuring consistent alignment.
The function opens the graphics device, renders the figure, and closes the
device via on.exit(), so the current interactive device is unaffected.
Value
Invisibly returns the normalised path to the saved file (character).
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
plot.fitverse for interactive display.
Examples
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
fit <- fitverse(x, plot = FALSE, verbose = FALSE)
save_plot(fit, file = tempfile(fileext = ".png"))
Serialise a fitverse Object to JSON
Description
Converts a fitverse object to a JSON string. Useful for passing
fit results to web front-ends, storing results in document databases, or
integrating with REST APIs.
The serialisation uses toJSON() on the output of
as.list.fitverse(), which strips non-serialisable internals
(raw optimiser fit objects, closures, environments) and returns a flat,
portable representation.
Usage
to_json(x, pretty = TRUE, ...)
## S3 method for class 'fitverse'
to_json(x, pretty = TRUE, ...)
Arguments
x |
An object with a |
pretty |
Logical: if |
... |
Additional arguments passed to |
Details
Requires the jsonlite package (listed in Suggests).
An informative error is raised if it is not installed.
The JSON output includes:
-
best_fit: distribution key, method, parameter estimates, loglik, AIC, BIC. -
ranking: full ranking data frame. -
data_summary: descriptive statistics. -
n,xlab,criterion.
The raw data vector is deliberately not included to keep the output compact and privacy-friendly for web contexts.
Value
A single character string containing the JSON representation of x.
Author(s)
Karuna G. Reddy karuna.reddy@auckland.ac.nz
M. G. M. Khan mgm.khan@usp.ac.fj
See Also
as.list.fitverse for the underlying list conversion.
fromJSON to parse the JSON back to R.
Examples
if (requireNamespace("jsonlite", quietly = TRUE)) {
set.seed(42)
x <- rgamma(300, shape = 2, rate = 0.5)
fit <- fitverse(x, plot = FALSE, verbose = FALSE)
json_str <- to_json(fit)
cat(substr(json_str, 1, 400))
# Round-trip back to R list
lst <- jsonlite::fromJSON(json_str)
lst$best_fit$params
}