Namespace provides a comprehensive collection of functions for performing statistical analysis in Clojure. It focuses on providing efficient implementations for common statistical tasks, leveraging fastmath's underlying numerical capabilities.
This namespace covers a wide range of statistical methods, including:
This namespace aims to provide a robust set of statistical tools for data analysis and modeling within the Clojure ecosystem.
Namespace provides a comprehensive collection of functions for
performing statistical analysis in Clojure. It focuses on providing efficient
implementations for common statistical tasks, leveraging fastmath's underlying
numerical capabilities.
This namespace covers a wide range of statistical methods, including:
* **Descriptive Statistics**: Measures of central tendency (mean, median, mode, expectile),
dispersion (variance, standard deviation, MAD, SEM), and shape (skewness, kurtosis, L-moments).
* **Quantiles and Percentiles**: Functions for calculating percentiles, quantiles, and the median,
including weighted versions and various estimation strategies.
* **Intervals and Extents**: Methods for defining ranges within data, such as span, IQR,
standard deviation/MAD/SEM extents, percentile/quantile intervals, prediction intervals (PI, HPDI),
and fence boundaries for outlier detection.
* **Outlier Detection**: Functions for identifying data points outside conventional fence boundaries.
* **Data Transformation**: Utilities for scaling, centering, trimming, winsorizing,
and applying power transformations (Box-Cox, Yeo-Johnson) to data.
* **Correlation and Covariance**: Measures of the linear and monotonic relationship
between two or more variables (Pearson, Spearman, Kendall), and functions for
generating covariance and correlation matrices.
* **Distance and Similarity Metrics**: Functions for quantifying differences or
likeness between data sequences or distributions, including error metrics (MAE, MSE, RMSE),
L-p norms, and various distribution dissimilarity/similarity measures.
* **Contingency Tables**: Functions for creating, analyzing, and deriving measures
of association and agreement (Cramer's V, Cohen's Kappa) from contingency tables,
including specialized functions for 2x2 tables.
* **Binary Classification Metrics**: Functions for generating confusion matrices
and calculating a wide array of performance metrics (Accuracy, Precision, Recall, F1, MCC, etc.).
* **Effect Size**: Measures quantifying the magnitude of statistical effects,
including difference-based (Cohen's d, Hedges' g, Glass's delta), ratio-based,
ordinal/non-parametric (Cliff's Delta, Vargha-Delaney A), and overlap-based (Cohen's U, p-overlap),
as well as measures related to explained variance (Eta-squared, Omega-squared, Cohen's f²).
* **Statistical Tests**: Functions for performing hypothesis tests, including:
- Normality and Shape tests (Skewness, Kurtosis, D'Agostino-Pearson K², Jarque-Bera, Bonett-Seier).
- Binomial tests and confidence intervals.
- Location tests (one-sample and two-sample T/Z tests, paired/unpaired).
- Variance tests (F-test, Levene's, Brown-Forsythe, Fligner-Killeen).
- Goodness-of-Fit and Independence tests (Power Divergence family including Chi-squared, G-test; AD/KS/CvM tests and their statistics).
- ANOVA and Rank Sum tests (One-way ANOVA, Kruskal-Wallis).
- Autocorrelation tests (Durbin-Watson).
* **Time Series Analysis**: Functions for analyzing the dependence structure of
time series data, such as Autocorrelation (ACF) and Partial Autocorrelation (PACF).
* **Histograms**: Functions for computing 1d and 2d (grid-based) histograms and estimating optimal binning strategies.
This namespace aims to provide a robust set of statistical tools for data analysis
and modeling within the Clojure ecosystem.(acf data)(acf data lags)Calculates the Autocorrelation Function (ACF) for a given time series data.
The ACF measures the linear dependence between a time series and its lagged values. It helps identify patterns (like seasonality or trend) and inform the selection of models for time series analysis (e.g., in ARIMA modeling).
Parameters:
data (seq of numbers): The time series data.lags (long or seq of longs, optional):
(m/dec (count data)).Returns a sequence of doubles: the autocorrelation coefficients for the specified lags. The value at lag 0 is always 1.0.
See also acf-ci (Calculates ACF with confidence intervals), pacf, pacf-ci.
Calculates the Autocorrelation Function (ACF) for a given time series `data`. The ACF measures the linear dependence between a time series and its lagged values. It helps identify patterns (like seasonality or trend) and inform the selection of models for time series analysis (e.g., in ARIMA modeling). Parameters: * `data` (seq of numbers): The time series data. * `lags` (long or seq of longs, optional): * If a number, calculates ACF for lags from 0 up to this maximum lag. * If a sequence of numbers, calculates ACF for each lag specified in the sequence. * If omitted (1-arity call), calculates ACF for lags from 0 up to `(m/dec (count data))`. Returns a sequence of doubles: the autocorrelation coefficients for the specified lags. The value at lag 0 is always 1.0. See also [[acf-ci]] (Calculates ACF with confidence intervals), [[pacf]], [[pacf-ci]].
(acf-ci data)(acf-ci data lags)(acf-ci data lags alpha)Calculates the Autocorrelation Function (ACF) for a time series and provides approximate confidence intervals.
This function computes the ACF of the input time series data for specified lags
(see acf) and includes approximate confidence intervals around the ACF
estimates. These intervals help determine whether the autocorrelation at a
specific lag is statistically significant (i.e., likely non-zero in the population).
Parameters:
data (seq of numbers): The time series data.lags (long or seq of longs, optional):
(dec (count data)).alpha (double, optional): The significance level for the confidence intervals.
Defaults to 0.05 (for a 95% CI).Returns a map containing:
:ci (double): The value of the approximate standard confidence interval bound
for lags > 0. If the absolute value of an ACF
coefficient at lag k > 0 exceeds this value, it is considered statistically significant.:acf (seq of doubles): The sequence of autocorrelation coefficients
at lags from 0 up to lags (or specified lags if lags is a sequence), calculated
using acf.:cis (seq of doubles): Cumulative confidence intervals for ACF. These are based on the
variance of the sum of squared sample autocorrelations up to each lag.Calculates the Autocorrelation Function (ACF) for a time series and provides approximate confidence intervals. This function computes the ACF of the input time series `data` for specified lags (see [[acf]]) and includes approximate confidence intervals around the ACF estimates. These intervals help determine whether the autocorrelation at a specific lag is statistically significant (i.e., likely non-zero in the population). Parameters: * `data` (seq of numbers): The time series data. * `lags` (long or seq of longs, optional): * If a number, calculates ACF for lags from 0 up to this maximum lag. * If a sequence of numbers, calculates ACF for each lag specified in the sequence. * If omitted (1-arity call), calculates ACF for lags from 0 up to `(dec (count data))`. * `alpha` (double, optional): The significance level for the confidence intervals. Defaults to `0.05` (for a 95% CI). Returns a map containing: * `:ci` (double): The value of the approximate standard confidence interval bound for lags > 0. If the absolute value of an ACF coefficient at lag `k > 0` exceeds this value, it is considered statistically significant. * `:acf` (seq of doubles): The sequence of autocorrelation coefficients at lags from 0 up to `lags` (or specified lags if `lags` is a sequence), calculated using [[acf]]. * `:cis` (seq of doubles): Cumulative confidence intervals for ACF. These are based on the variance of the sum of squared sample autocorrelations up to each lag. See also [[acf]], [[pacf]], [[pacf-ci]].
(ad-statistic xs distribution)(ad-statistic xs distribution {:keys [variant sorted?] :or {variant :ad}})Calculates the Anderson-Darling statistic, or one of its variants, of a sample against a distribution.
The statistic gives more weight to the tails of the distribution than cvm-statistic. The default :ad is the classic A2, the one returned by ad-test-one-sample. The variants put the weight on one tail only (:adr right, :adl left) or use second-order weights (:ad2r, :ad2l, :ad2), as used for the minimum goodness-of-fit estimation of distribution parameters. The upper tail probabilities are taken from ccdf, which keeps the precision in the right tail.
Parameters:
xs (sequence of numbers): The sample.distribution: A fastmath.random distribution.opts (map, optional):
:variant (keyword, default :ad): One of :ad, :adr, :adl, :ad2r, :ad2l, :ad2.:sorted? (boolean, default false): Set to true when xs is already sorted ascending, to skip sorting.Returns the statistic as a double. A NaN result, which comes from a distribution whose cumulative distribution function is 0 or 1 at observations, is returned as ##Inf, so the value can be minimized. Throws ex-info for empty xs or an unknown :variant.
For discrete and mixed distributions the statistic is still computed from the cumulative distribution function, but it is only descriptive.
See also ad-test-one-sample, ks-statistic, cvm-statistic.
Calculates the Anderson-Darling statistic, or one of its variants, of a sample against a distribution. The statistic gives more weight to the tails of the distribution than [[cvm-statistic]]. The default `:ad` is the classic `A2`, the one returned by [[ad-test-one-sample]]. The variants put the weight on one tail only (`:adr` right, `:adl` left) or use second-order weights (`:ad2r`, `:ad2l`, `:ad2`), as used for the minimum goodness-of-fit estimation of distribution parameters. The upper tail probabilities are taken from `ccdf`, which keeps the precision in the right tail. Parameters: - `xs` (sequence of numbers): The sample. - `distribution`: A `fastmath.random` distribution. - `opts` (map, optional): - `:variant` (keyword, default `:ad`): One of `:ad`, `:adr`, `:adl`, `:ad2r`, `:ad2l`, `:ad2`. - `:sorted?` (boolean, default `false`): Set to `true` when `xs` is already sorted ascending, to skip sorting. Returns the statistic as a double. A `NaN` result, which comes from a distribution whose cumulative distribution function is `0` or `1` at observations, is returned as `##Inf`, so the value can be minimized. Throws `ex-info` for empty `xs` or an unknown `:variant`. For discrete and mixed distributions the statistic is still computed from the cumulative distribution function, but it is only descriptive. See also [[ad-test-one-sample]], [[ks-statistic]], [[cvm-statistic]].
(ad-test-one-sample xs)(ad-test-one-sample xs distribution-or-ys)(ad-test-one-sample xs
distribution-or-ys
{:keys [sides kernel bandwidth]
:or {sides :right kernel :gaussian}})Performs the Anderson-Darling (AD) test for goodness-of-fit.
This test assesses the null hypothesis that a sample xs comes from a
specified theoretical distribution or another empirical distribution. It is
sensitive to differences in the tails of the distributions.
Parameters:
xs (seq of numbers): The sample data to be tested.distribution-or-ys (optional):
fastmath.random distribution object to test against. If omitted, defaults
to the standard normal distribution (fastmath.random/default-normal).ys). In this case, an empirical distribution is
estimated from ys using Kernel Density Estimation (KDE) or an enumerated
distribution (see :kernel option).opts (map, optional): Options map:
:sides (keyword, default :right): Specifies the side(s) of the
A^2 statistic's distribution used for p-value calculation.
:right (default): Tests if the observed A^2 statistic is significantly
large (standard approach for AD test, indicating poor fit).:left: Tests if the observed A^2 statistic is significantly small.:two-sided: Tests if the observed A^2 statistic is extreme in either tail.:kernel (keyword, default :gaussian): Used only when distribution-or-ys
is a sequence. Specifies the method to estimate the empirical distribution:
:gaussian (or other KDE kernels): Uses Kernel Density Estimation.:enumerated: Creates a discrete empirical distribution from ys.:bandwidth (double, optional): Bandwidth for KDE (if applicable).Returns a map containing:
:A2: The Anderson-Darling test statistic (A^2).:stat: Alias for :A2.:p-value: The p-value associated with the test statistic and the specified :sides.:n: Sample size of xs.:mean: Mean of the sample xs (for context).:stddev: Standard deviation of the sample xs (for context).:sides: The alternative hypothesis side used for p-value calculation.Performs the Anderson-Darling (AD) test for goodness-of-fit.
This test assesses the null hypothesis that a sample `xs` comes from a
specified theoretical distribution or another empirical distribution. It is
sensitive to differences in the tails of the distributions.
Parameters:
- `xs` (seq of numbers): The sample data to be tested.
- `distribution-or-ys` (optional):
- A `fastmath.random` distribution object to test against. If omitted, defaults
to the standard normal distribution (`fastmath.random/default-normal`).
- A sequence of numbers (`ys`). In this case, an empirical distribution is
estimated from `ys` using Kernel Density Estimation (KDE) or an enumerated
distribution (see `:kernel` option).
- `opts` (map, optional): Options map:
- `:sides` (keyword, default `:right`): Specifies the side(s) of the
A^2 statistic's distribution used for p-value calculation.
- `:right` (default): Tests if the observed A^2 statistic is significantly
large (standard approach for AD test, indicating poor fit).
- `:left`: Tests if the observed A^2 statistic is significantly small.
- `:two-sided`: Tests if the observed A^2 statistic is extreme in either tail.
- `:kernel` (keyword, default `:gaussian`): Used only when `distribution-or-ys`
is a sequence. Specifies the method to estimate the empirical distribution:
- `:gaussian` (or other KDE kernels): Uses Kernel Density Estimation.
- `:enumerated`: Creates a discrete empirical distribution from `ys`.
- `:bandwidth` (double, optional): Bandwidth for KDE (if applicable).
Returns a map containing:
- `:A2`: The Anderson-Darling test statistic (A^2).
- `:stat`: Alias for `:A2`.
- `:p-value`: The p-value associated with the test statistic and the specified `:sides`.
- `:n`: Sample size of `xs`.
- `:mean`: Mean of the sample `xs` (for context).
- `:stddev`: Standard deviation of the sample `xs` (for context).
- `:sides`: The alternative hypothesis side used for p-value calculation.(adjacent-values vs)(adjacent-values vs estimation-strategy)(adjacent-values vs q1 q3 m)Calculates the lower and upper adjacent values (LAV and UAV) of vs, together with its median.
LAV and UAV are the actual data values used as whisker endpoints in a Tukey box-and-whisker plot: rather than the inner-fence thresholds themselves (see inner-fence-extent), they are the most extreme observed values that still fall within those thresholds. Let Q1 and Q3 be the 25th and 75th percentiles and IQR = Q3 - Q1:
vs that is greater than or equal to the lower inner fence, Q1 - 1.5*IQR.vs that is less than or equal to the upper inner fence, Q3 + 1.5*IQR.Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.q1, q3, m (doubles): Precomputed first quartile, third quartile, and median, used instead of computing them from vs.Returns a 3-element vector [LAV UAV median].
See also inner-fence-extent, outer-fence-extent, iqr, percentile-extent.
Calculates the lower and upper adjacent values (LAV and UAV) of `vs`, together with its median. LAV and UAV are the actual data values used as whisker endpoints in a Tukey box-and-whisker plot: rather than the inner-fence thresholds themselves (see [[inner-fence-extent]]), they are the most extreme observed values that still fall within those thresholds. Let `Q1` and `Q3` be the 25th and 75th percentiles and `IQR = Q3 - Q1`: - LAV is the smallest value in `vs` that is greater than or equal to the lower inner fence, `Q1 - 1.5*IQR`. - UAV is the largest value in `vs` that is less than or equal to the upper inner fence, `Q3 + 1.5*IQR`. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. - `q1`, `q3`, `m` (doubles): Precomputed first quartile, third quartile, and median, used instead of computing them from `vs`. Returns a 3-element vector `[LAV UAV median]`. See also [[inner-fence-extent]], [[outer-fence-extent]], [[iqr]], [[percentile-extent]].
(ameasure [group1 group2])(ameasure group1 group2)Calculates the Vargha-Delaney A measure for two independent samples.
A non-parametric effect size measure quantifying the probability that a randomly chosen value from the first sample (group1) is greater than a randomly chosen value from the second sample (group2).
Parameters:
group1: The first independent sample.group2: The second independent sample.Returns the calculated A measure (a double) in the range [0, 1].
A value of 0.5 indicates stochastic equality (distributions are overlapping). Values > 0.5 mean group1 tends to be larger; values < 0.5 mean group2 tends to be larger.
Related to cliffs-delta and the Wilcoxon-Mann-Whitney U test statistic.
See also cliffs-delta, wmw-odds.
Calculates the Vargha-Delaney A measure for two independent samples. A non-parametric effect size measure quantifying the probability that a randomly chosen value from the first sample (`group1`) is greater than a randomly chosen value from the second sample (`group2`). Parameters: - `group1`: The first independent sample. - `group2`: The second independent sample. Returns the calculated A measure (a double) in the range [0, 1]. A value of 0.5 indicates stochastic equality (distributions are overlapping). Values > 0.5 mean `group1` tends to be larger; values < 0.5 mean `group2` tends to be larger. Related to [[cliffs-delta]] and the Wilcoxon-Mann-Whitney U test statistic. See also [[cliffs-delta]], [[wmw-odds]].
(anova-cohens-f xss)(anova-cohens-f xss type)Calculates Cohen's f, a measure of effect size derived as the square root of Cohen's f² (anova-cohens-f2) for a one-way ANOVA design.
Cohen's f is a standardized measure quantifying the magnitude of the effect of group membership on the (numeric) dependent variable. It is the multi-group, categorical-predictor counterpart of cohens-f.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in one-way-anova-test.type (keyword or function, optional): Specifies the measure of 'Proportion of Variance Explained' used in the underlying anova-cohens-f2 calculation. Defaults to :eta.
:eta (default): Uses Eta-squared (correlation ratio), a measure of variance explained in the sample.:omega: Uses Omega-squared, a less biased estimate of variance explained in the population.:epsilon: Uses Epsilon-squared, another less biased estimate of variance explained in the population.xss and returning a double representing the proportion of variance explained.Returns the calculated Cohen's f effect size as a double. Values range from 0.0 upwards.
Interpretation:
See also anova-cohens-f2, anova-eta-sq, anova-omega-sq, anova-epsilon-sq, cohens-f.
Calculates Cohen's f, a measure of effect size derived as the square root of Cohen's f² ([[anova-cohens-f2]]) for a one-way ANOVA design.
Cohen's f is a standardized measure quantifying the magnitude of the effect of group membership on the (numeric) dependent variable. It is the multi-group, categorical-predictor counterpart of [[cohens-f]].
Parameters:
- `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in [[one-way-anova-test]].
- `type` (keyword or function, optional): Specifies the measure of 'Proportion of Variance Explained' used in the underlying [[anova-cohens-f2]] calculation. Defaults to `:eta`.
- `:eta` (default): Uses Eta-squared (correlation ratio), a measure of variance explained in the sample.
- `:omega`: Uses Omega-squared, a less biased estimate of variance explained in the population.
- `:epsilon`: Uses Epsilon-squared, another less biased estimate of variance explained in the population.
- Any function: A function accepting `xss` and returning a double representing the proportion of variance explained.
Returns the calculated Cohen's f effect size as a double. Values range from `0.0` upwards.
Interpretation:
- Cohen's guidelines for interpreting the magnitude of f² (and by extension, f) are:
- $f = 0.10$ (approx. $f^2 = 0.01$): small effect
- $f = 0.25$ (approx. $f^2 = 0.0625$): medium effect
- $f = 0.40$ (approx. $f^2 = 0.16$): large effect
(Note: Guidelines are often quoted for f², interpret f as $\sqrt{f^2}$)
See also [[anova-cohens-f2]], [[anova-eta-sq]], [[anova-omega-sq]], [[anova-epsilon-sq]], [[cohens-f]].(anova-cohens-f2 xss)(anova-cohens-f2 xss type)Calculates Cohen's f², a measure of effect size for a one-way ANOVA design.
Cohen's f² quantifies the magnitude of the effect of group membership on the (numeric) dependent variable, expressed as the ratio of the variance explained by the effect to the unexplained variance. It is the multi-group, categorical-predictor counterpart of cohens-f2.
This function allows calculating f² using different measures for the 'Proportion of Variance Explained', specified by the type parameter:
:eta (default): Uses anova-eta-sq (Eta-squared / correlation ratio), a measure of the proportion of variance explained in the sample.:omega: Uses anova-omega-sq (Omega-squared), a less biased estimate of the proportion of variance explained in the population.:epsilon: Uses anova-epsilon-sq (Epsilon-squared), another less biased estimate of the proportion of variance explained in the population.xss and returning a double representing the proportion of variance explained.Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in one-way-anova-test.type (keyword or function, optional): Specifies the measure of 'Proportion of Variance Explained' to use (:eta, :omega, :epsilon or any function). Defaults to :eta.Returns the calculated Cohen's f² effect size as a double. Values range from 0.0 upwards.
Interpretation Guidelines (approximate, often used for F-tests in ANOVA):
See also anova-cohens-f, anova-eta-sq, anova-omega-sq, anova-epsilon-sq, cohens-f2.
Calculates Cohen's f², a measure of effect size for a one-way ANOVA design. Cohen's f² quantifies the magnitude of the effect of group membership on the (numeric) dependent variable, expressed as the ratio of the variance explained by the effect to the unexplained variance. It is the multi-group, categorical-predictor counterpart of [[cohens-f2]]. This function allows calculating f² using different measures for the 'Proportion of Variance Explained', specified by the `type` parameter: - `:eta` (default): Uses [[anova-eta-sq]] (Eta-squared / correlation ratio), a measure of the proportion of variance explained in the sample. - `:omega`: Uses [[anova-omega-sq]] (Omega-squared), a less biased estimate of the proportion of variance explained in the population. - `:epsilon`: Uses [[anova-epsilon-sq]] (Epsilon-squared), another less biased estimate of the proportion of variance explained in the population. - Any function: A function accepting `xss` and returning a double representing the proportion of variance explained. Parameters: - `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in [[one-way-anova-test]]. - `type` (keyword or function, optional): Specifies the measure of 'Proportion of Variance Explained' to use (`:eta`, `:omega`, `:epsilon` or any function). Defaults to `:eta`. Returns the calculated Cohen's f² effect size as a double. Values range from `0.0` upwards. Interpretation Guidelines (approximate, often used for F-tests in ANOVA): - $f^2 = 0.02$: small effect - $f^2 = 0.15$: medium effect - $f^2 = 0.35$: large effect See also [[anova-cohens-f]], [[anova-eta-sq]], [[anova-omega-sq]], [[anova-epsilon-sq]], [[cohens-f2]].
(anova-epsilon-sq xss)Calculates Epsilon-squared (ε²), a less biased effect size for a one-way ANOVA design.
Epsilon-squared estimates the proportion of variance in the (numeric) dependent variable that is accounted for by group membership (the categorical independent variable) in the population, correcting for the upward bias of anova-eta-sq. It plays the same role for genuinely grouped (categorical) data as epsilon-sq does for a pair of numeric sequences related by simple linear regression.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in one-way-anova-test.Returns the calculated Epsilon-squared value as a double, within [0.0, 1.0]. Following common convention (e.g. R's effectsize package), a theoretically-possible negative estimate (which can occur when the true effect is close to zero) is clamped to 0.0.
See also anova-eta-sq, anova-omega-sq, anova-cohens-f2, anova-cohens-f, one-way-anova-test, epsilon-sq (pairwise regression-based measure with a similar name but different design), rank-epsilon-sq (rank-based analogue).
Calculates Epsilon-squared (ε²), a less biased effect size for a one-way ANOVA design. Epsilon-squared estimates the proportion of variance in the (numeric) dependent variable that is accounted for by group membership (the categorical independent variable) in the population, correcting for the upward bias of [[anova-eta-sq]]. It plays the same role for genuinely grouped (categorical) data as [[epsilon-sq]] does for a pair of numeric sequences related by simple linear regression. Parameters: - `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in [[one-way-anova-test]]. Returns the calculated Epsilon-squared value as a double, within `[0.0, 1.0]`. Following common convention (e.g. R's `effectsize` package), a theoretically-possible negative estimate (which can occur when the true effect is close to zero) is clamped to `0.0`. See also [[anova-eta-sq]], [[anova-omega-sq]], [[anova-cohens-f2]], [[anova-cohens-f]], [[one-way-anova-test]], [[epsilon-sq]] (pairwise regression-based measure with a similar name but different design), [[rank-epsilon-sq]] (rank-based analogue).
(anova-eta-sq xss)Calculates Eta-squared (η²), the correlation ratio effect size for a one-way ANOVA design.
Eta-squared is the classical correlation ratio: the proportion of the total variance in the (numeric) dependent variable that is accounted for by group membership (the categorical independent variable). Unlike eta-sq (which fits a straight-line regression between two numeric sequences), this function treats xss as a genuine grouping of observations, exactly as used by one-way-anova-test and kruskal-test, so it correctly captures non-linear (arbitrary group-mean) relationships between the grouping variable and the outcome.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations.Returns the calculated Eta-squared value as a double, always within [0.0, 1.0].
Interpretation:
0.0 indicates that group membership explains none of the variance in the outcome.1.0 indicates that group membership explains all of the variance in the outcome (all within-group variance is zero).Eta-squared is a sample-based estimate and tends to overestimate the population effect size, especially with small samples or many groups; anova-omega-sq and anova-epsilon-sq provide less biased alternatives.
See also anova-omega-sq, anova-epsilon-sq, anova-cohens-f2, anova-cohens-f, one-way-anova-test, rank-eta-sq (rank-based analogue), eta-sq (pairwise regression-based measure with a similar name but different design).
Calculates Eta-squared (η²), the correlation ratio effect size for a one-way ANOVA design. Eta-squared is the classical correlation ratio: the proportion of the total variance in the (numeric) dependent variable that is accounted for by group membership (the categorical independent variable). Unlike [[eta-sq]] (which fits a straight-line regression between two numeric sequences), this function treats `xss` as a genuine grouping of observations, exactly as used by [[one-way-anova-test]] and [[kruskal-test]], so it correctly captures non-linear (arbitrary group-mean) relationships between the grouping variable and the outcome. Parameters: - `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations. Returns the calculated Eta-squared value as a double, always within `[0.0, 1.0]`. Interpretation: - `0.0` indicates that group membership explains none of the variance in the outcome. - `1.0` indicates that group membership explains all of the variance in the outcome (all within-group variance is zero). Eta-squared is a sample-based estimate and tends to overestimate the population effect size, especially with small samples or many groups; [[anova-omega-sq]] and [[anova-epsilon-sq]] provide less biased alternatives. See also [[anova-omega-sq]], [[anova-epsilon-sq]], [[anova-cohens-f2]], [[anova-cohens-f]], [[one-way-anova-test]], [[rank-eta-sq]] (rank-based analogue), [[eta-sq]] (pairwise regression-based measure with a similar name but different design).
(anova-omega-sq xss)Calculates Omega-squared (ω²), a less biased effect size for a one-way ANOVA design.
Omega-squared estimates the proportion of variance in the (numeric) dependent variable that is accounted for by group membership (the categorical independent variable) in the population, correcting for the upward bias of anova-eta-sq. It plays the same role for genuinely grouped (categorical) data as omega-sq does for a pair of numeric sequences related by simple linear regression.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in one-way-anova-test.Returns the calculated Omega-squared value as a double, within [0.0, 1.0]. Following common convention (e.g. R's effectsize package), a theoretically-possible negative estimate (which can occur when the true effect is close to zero) is clamped to 0.0.
See also anova-eta-sq, anova-epsilon-sq, anova-cohens-f2, anova-cohens-f, one-way-anova-test, omega-sq (pairwise regression-based measure with a similar name but different design).
Calculates Omega-squared (ω²), a less biased effect size for a one-way ANOVA design. Omega-squared estimates the proportion of variance in the (numeric) dependent variable that is accounted for by group membership (the categorical independent variable) in the population, correcting for the upward bias of [[anova-eta-sq]]. It plays the same role for genuinely grouped (categorical) data as [[omega-sq]] does for a pair of numeric sequences related by simple linear regression. Parameters: - `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in [[one-way-anova-test]]. Returns the calculated Omega-squared value as a double, within `[0.0, 1.0]`. Following common convention (e.g. R's `effectsize` package), a theoretically-possible negative estimate (which can occur when the true effect is close to zero) is clamped to `0.0`. See also [[anova-eta-sq]], [[anova-epsilon-sq]], [[anova-cohens-f2]], [[anova-cohens-f]], [[one-way-anova-test]], [[omega-sq]] (pairwise regression-based measure with a similar name but different design).
(auc performance)(auc x-axis y-axis)(auc performance x-axis y-axis)Calculates the Area Under the Curve (AUC) using trapezoidal integration.
The curve is defined by an x-axis and a y-axis, each resolved from a performance map, a plain sequence of values, or a metric function. Common use cases are:
x-axis = :fpr, y-axis = :tprx-axis = :recall, y-axis = :precisionx-axis = :fpr, y-axis = :fnrParameters:
performance - a performance map returned by binary-measures-thr; when called with
one argument, defaults to the ROC curve (:fpr vs :tpr).x-axis, y-axis - each can be:
performance (e.g. :fpr, :tpr, :recall, :precision, :fnr)tp, fp, fn, tn (called with the four columns from performance) that returns a sequence of values[x-axis y-axis] - when called with two arguments and no performance map, treats both as
plain sequences of coordinates and integrates directly.Returns the AUC as a double. The value is not constrained; it depends on the direction and
range of the input axes. For a standard ROC curve the result lies in [0.0, 1.0].
Returns 0.0 for an empty or single-point input.
See also auc-roc, binary-measures-thr, multiclass-auc.
Calculates the Area Under the Curve (AUC) using trapezoidal integration. The curve is defined by an x-axis and a y-axis, each resolved from a performance map, a plain sequence of values, or a metric function. Common use cases are: - ROC curve (default): `x-axis` = `:fpr`, `y-axis` = `:tpr` - Precision-Recall curve: `x-axis` = `:recall`, `y-axis` = `:precision` - DET curve: `x-axis` = `:fpr`, `y-axis` = `:fnr` Parameters: - `performance` - a performance map returned by [[binary-measures-thr]]; when called with one argument, defaults to the ROC curve (`:fpr` vs `:tpr`). - `x-axis`, `y-axis` - each can be: - a keyword looked up in `performance` (e.g. `:fpr`, `:tpr`, `:recall`, `:precision`, `:fnr`) - a sequence of numeric values used directly as axis coordinates - a function of `tp`, `fp`, `fn`, `tn` (called with the four columns from `performance`) that returns a sequence of values - `[x-axis y-axis]` - when called with two arguments and no `performance` map, treats both as plain sequences of coordinates and integrates directly. Returns the AUC as a double. The value is not constrained; it depends on the direction and range of the input axes. For a standard ROC curve the result lies in `[0.0, 1.0]`. Returns `0.0` for an empty or single-point input. See also [[auc-roc]], [[binary-measures-thr]], [[multiclass-auc]].
(auc-roc labels scores)(auc-roc labels scores true-value)Calculates the ROC AUC (Area Under the Receiver Operating Characteristic Curve) using the U-statistic (Wilcoxon-Mann-Whitney statistic).
This method computes AUC directly from labels and continuous scores without constructing the ROC curve explicitly.
It is equivalent to the probability that a randomly chosen positive instance is ranked higher than a randomly chosen negative instance.
The result is constrained to [0.0, 1.0].
Parameters:
labels - a sequence of class labels (binary).scores - a sequence of continuous scores or predicted probabilities, one per label.true-value - (optional) the label value to treat as positive; when nil, the positive class is inferred via [[binary-process-list]].Returns the AUC score as a double in the range [0.0, 1.0]. A value of 1.0 means perfect ranking,
0.5 corresponds to a random classifier, and values below 0.5 indicate worse-than-random ranking.
Returns 0.0 when there are no positive or no negative examples.
See also auc, binary-measures-thr, multiclass-auc.
Calculates the ROC AUC (Area Under the Receiver Operating Characteristic Curve) using the U-statistic (Wilcoxon-Mann-Whitney statistic). This method computes AUC directly from labels and continuous scores without constructing the ROC curve explicitly. It is equivalent to the probability that a randomly chosen positive instance is ranked higher than a randomly chosen negative instance. The result is constrained to `[0.0, 1.0]`. Parameters: - `labels` - a sequence of class labels (binary). - `scores` - a sequence of continuous scores or predicted probabilities, one per label. - `true-value` - (optional) the label value to treat as positive; when `nil`, the positive class is inferred via [[binary-process-list]]. Returns the AUC score as a double in the range `[0.0, 1.0]`. A value of `1.0` means perfect ranking, `0.5` corresponds to a random classifier, and values below `0.5` indicate worse-than-random ranking. Returns `0.0` when there are no positive or no negative examples. See also [[auc]], [[binary-measures-thr]], [[multiclass-auc]].
(binary-measures confusion-matrix)(binary-measures actual prediction)(binary-measures actual prediction true-value)(binary-measures tp fn fp tn)Calculates a selected subset of common evaluation metrics for binary classification results.
This function is a convenience wrapper around binary-measures-all, providing
a map containing the most frequently used metrics derived from a 2x2 confusion matrix.
The 2x2 confusion matrix is based on True Positives (TP), False Positives (FP), False Negatives (FN), and True Negatives (TN):
| Predicted True | Predicted False | |
|---|---|---|
| Actual True | TP | FN |
| Actual False | FP | TN |
The function accepts the same input formats as binary-measures-all:
(binary-measures tp fn fp tn): Direct input of the four counts.(binary-measures confusion-matrix): Input as a structured representation
(map with keys like :tp, :fn, :fp, :tn; sequence of sequences
[ [TP FP] [FN TN] ]; or flat sequence [TP FN FP TN]).(binary-measures actual prediction): Input as two sequences of outcomes.(binary-measures actual prediction true-value): Input as two sequences with
a specified encoding for true (success).Parameters:
tp, fn, fp, tn (long): Counts from the confusion matrix.confusion-matrix (map or sequence): Representation of the confusion matrix.actual, prediction (sequences): Sequences of true and predicted outcomes.true-value (optional): Specifies how outcomes are converted to boolean true/false.Returns a map containing the following selected metrics:
:tp (True Positives):tn (True Negatives):fp (False Positives):fn (False Negatives):accuracy:fdr (False Discovery Rate, 1 - Precision):f-measure (F1 Score, harmonic mean of Precision and Recall):fall-out (False Positive Rate):precision (Positive Predictive Value):recall (True Positive Rate / Sensitivity):sensitivity (Alias for Recall/TPR):specificity (True Negative Rate):prevalence (Proportion of positive cases)See also confusion-matrix, binary-measures-all, mcc, contingency-2x2-measures-all.
Calculates a selected subset of common evaluation metrics for binary classification results.
This function is a convenience wrapper around [[binary-measures-all]], providing
a map containing the most frequently used metrics derived from a 2x2 confusion matrix.
The 2x2 confusion matrix is based on True Positives (TP), False Positives (FP),
False Negatives (FN), and True Negatives (TN):
| | Predicted True | Predicted False |
|:---------------|:---------------|:----------------|
| **Actual True** | TP | FN |
| **Actual False** | FP | TN |
The function accepts the same input formats as [[binary-measures-all]]:
1. `(binary-measures tp fn fp tn)`: Direct input of the four counts.
2. `(binary-measures confusion-matrix)`: Input as a structured representation
(map with keys like `:tp`, `:fn`, `:fp`, `:tn`; sequence of sequences
`[ [TP FP] [FN TN] ]`; or flat sequence `[TP FN FP TN]`).
3. `(binary-measures actual prediction)`: Input as two sequences of outcomes.
4. `(binary-measures actual prediction true-value)`: Input as two sequences with
a specified encoding for `true` (success).
Parameters:
- `tp, fn, fp, tn` (long): Counts from the confusion matrix.
- `confusion-matrix` (map or sequence): Representation of the confusion matrix.
- `actual`, `prediction` (sequences): Sequences of true and predicted outcomes.
- `true-value` (optional): Specifies how outcomes are converted to boolean `true`/`false`.
Returns a map containing the following selected metrics:
- `:tp` (True Positives)
- `:tn` (True Negatives)
- `:fp` (False Positives)
- `:fn` (False Negatives)
- `:accuracy`
- `:fdr` (False Discovery Rate, 1 - Precision)
- `:f-measure` (F1 Score, harmonic mean of Precision and Recall)
- `:fall-out` (False Positive Rate)
- `:precision` (Positive Predictive Value)
- `:recall` (True Positive Rate / Sensitivity)
- `:sensitivity` (Alias for Recall/TPR)
- `:specificity` (True Negative Rate)
- `:prevalence` (Proportion of positive cases)
See also [[confusion-matrix]], [[binary-measures-all]], [[mcc]], [[contingency-2x2-measures-all]].(binary-measures-all confusion-matrix)(binary-measures-all actual prediction)(binary-measures-all actual prediction true-value)(binary-measures-all tp fn fp tn)Calculates a comprehensive set of evaluation metrics for binary classification results.
This function computes various statistics derived from a 2x2 confusion matrix, summarizing the performance of a binary classifier.
The 2x2 confusion matrix is based on True Positives (TP), False Positives (FP), False Negatives (FN), and True Negatives (TN):
| Predicted True | Predicted False | |
|---|---|---|
| Actual True | TP | FN |
| Actual False | FP | TN |
The function supports several input formats:
(binary-measures-all tp fn fp tn): Direct input of the four counts as arguments.
tp (long): True Positive count.fn (long): False Negative count.fp (long): False Positive count.tn (long): True Negative count.(binary-measures-all confusion-matrix): Input as a structured representation of the confusion matrix.
confusion-matrix: Can be:
:tp, :fn, :fp, :tn (e.g., {:tp 10 :fn 2 :fp 5 :tn 80}).[[TP FP] [FN TN]] (e.g., [[10 5] [2 80]]).[TP FN FP TN] (e.g., [10 2 5 80]).(binary-measures-all actual prediction): Input as two sequences of outcomes.
actual (sequence): Sequence of true outcomes.prediction (sequence): Sequence of predicted outcomes. Must have the same length as actual.
Values in actual and prediction are converted to boolean true/false. By default,
any non-nil or non-zero numeric value is treated as true, and nil or 0.0 is
treated as false.(binary-measures-all actual prediction true-value): Input as two sequences with a specified encoding for true.
actual, prediction: Sequences as in the previous arity.true-value (optional): Specifies how values in actual and prediction are converted to boolean true (success) or false (failure).
nil (default): Non-nil/non-zero (for numbers) is true.false, the value is false.true if the value satisfies the predicate.Returns a map containing a wide array of calculated metrics. This includes, but is not limited to:
:tp, :fn, :fp, :tn:cp (Actual Positives), :cn (Actual Negatives), :pcp (Predicted Positives), :pcn (Predicted Negatives), :total (Grand Total):tpr (True Positive Rate, Recall, Sensitivity, Hit Rate):fnr (False Negative Rate, Miss Rate):fpr (False Positive Rate, Fall-out):tnr (True Negative Rate, Specificity, Selectivity):ppv (Positive Predictive Value, Precision):fdr (False Discovery Rate, 1 - ppv):npv (Negative Predictive Value):for (False Omission Rate, 1 - npv):lr+ (Positive Likelihood Ratio):lr- (Negative Likelihood Ratio):dor (Diagnostic Odds Ratio):accuracy:ba (Balanced Accuracy):fm (Fowlkes–Mallows index):pt (Prevalence Threshold):ts (Threat Score, Jaccard index):f-measure / :f1-score (F1 Score, special case of F-beta score):f-beta (Function to calculate F-beta for any beta):mcc / :phi (Matthews Correlation Coefficient, Phi coefficient):bm (Bookmaker Informedness):kappa (Cohen's Kappa, for 2x2 table):mk (Markedness)Metrics are generally calculated using standard formulas based on the TP, FN, FP, TN counts. For more details on specific metrics, refer to standard classification literature or the Wikipedia page on Precision and recall, which covers many of these concepts.
See also confusion-matrix, binary-measures (for a selected subset of metrics),
mcc, contingency-2x2-measures-all (for a broader set of 2x2 table measures).
Calculates a comprehensive set of evaluation metrics for binary classification results.
This function computes various statistics derived from a 2x2 confusion matrix,
summarizing the performance of a binary classifier.
The 2x2 confusion matrix is based on True Positives (TP), False Positives (FP),
False Negatives (FN), and True Negatives (TN):
| | Predicted True | Predicted False |
|:---------------|:---------------|:----------------|
| **Actual True** | TP | FN |
| **Actual False** | FP | TN |
The function supports several input formats:
1. `(binary-measures-all tp fn fp tn)`: Direct input of the four counts as arguments.
- `tp` (long): True Positive count.
- `fn` (long): False Negative count.
- `fp` (long): False Positive count.
- `tn` (long): True Negative count.
2. `(binary-measures-all confusion-matrix)`: Input as a structured representation of the confusion matrix.
- `confusion-matrix`: Can be:
- A map with keys like `:tp`, `:fn`, `:fp`, `:tn` (e.g., `{:tp 10 :fn 2 :fp 5 :tn 80}`).
- A sequence of sequences representing rows `[[TP FP] [FN TN]]` (e.g., `[[10 5] [2 80]]`).
- A flat sequence `[TP FN FP TN]` (e.g., `[10 2 5 80]`).
3. `(binary-measures-all actual prediction)`: Input as two sequences of outcomes.
- `actual` (sequence): Sequence of true outcomes.
- `prediction` (sequence): Sequence of predicted outcomes. Must have the same length as `actual`.
Values in `actual` and `prediction` are converted to boolean `true`/`false`. By default,
any non-`nil` or non-zero numeric value is treated as `true`, and `nil` or `0.0` is
treated as `false`.
4. `(binary-measures-all actual prediction true-value)`: Input as two sequences with a specified encoding for `true`.
- `actual`, `prediction`: Sequences as in the previous arity.
- `true-value` (optional): Specifies how values in `actual` and `prediction` are converted to boolean `true` (success) or `false` (failure).
- `nil` (default): Non-`nil`/non-zero (for numbers) is true.
- Any sequence/set: Values found in this collection are true.
- A map: Values are mapped according to the map; if a key is not found or maps to `false`, the value is false.
- A predicate function: Returns `true` if the value satisfies the predicate.
Returns a map containing a wide array of calculated metrics. This includes, but is not limited to:
- Basic Counts: `:tp`, `:fn`, `:fp`, `:tn`
- Totals: `:cp` (Actual Positives), `:cn` (Actual Negatives), `:pcp` (Predicted Positives), `:pcn` (Predicted Negatives), `:total` (Grand Total)
- Rates (often ratios of counts):
- `:tpr` (True Positive Rate, Recall, Sensitivity, Hit Rate)
- `:fnr` (False Negative Rate, Miss Rate)
- `:fpr` (False Positive Rate, Fall-out)
- `:tnr` (True Negative Rate, Specificity, Selectivity)
- `:ppv` (Positive Predictive Value, Precision)
- `:fdr` (False Discovery Rate, `1 - ppv`)
- `:npv` (Negative Predictive Value)
- `:for` (False Omission Rate, `1 - npv`)
- Ratios/Odds:
- `:lr+` (Positive Likelihood Ratio)
- `:lr-` (Negative Likelihood Ratio)
- `:dor` (Diagnostic Odds Ratio)
- Combined Scores:
- `:accuracy`
- `:ba` (Balanced Accuracy)
- `:fm` (Fowlkes–Mallows index)
- `:pt` (Prevalence Threshold)
- `:ts` (Threat Score, Jaccard index)
- `:f-measure` / `:f1-score` (F1 Score, special case of F-beta score)
- `:f-beta` (Function to calculate F-beta for any beta)
- `:mcc` / `:phi` (Matthews Correlation Coefficient, Phi coefficient)
- `:bm` (Bookmaker Informedness)
- `:kappa` (Cohen's Kappa, for 2x2 table)
- `:mk` (Markedness)
Metrics are generally calculated using standard formulas based on the TP, FN, FP, TN counts.
For more details on specific metrics, refer to standard classification literature or
the Wikipedia page on [Precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall),
which covers many of these concepts.
See also [[confusion-matrix]], [[binary-measures]] (for a selected subset of metrics),
[[mcc]], [[contingency-2x2-measures-all]] (for a broader set of 2x2 table measures).
(binary-measures-thr labels scores)(binary-measures-thr labels scores true-value)Calculate binary metrics at given thresholds (a performance).
Each measure is a sequence with value for given threshold. Ties are interpolated lineary.
A true-value determines which label(s) is true.
Curves:
:fpr and :tpr:recall and :precision:fpr and :fnrReturned measures contain:
:thr - thresholds:p, :n, :total:tp, :fp, :fn, :tn:tpr/:recall/:sensitivity, :fnr/:miss-rate, :fpr/:fallout, :tnr/:specificity:ppv/:precision, :fdr, :for, :npv:mcc:f1-score:kappa:fm:ts/:jaccardCalculate binary metrics at given thresholds (a performance). Each measure is a sequence with value for given threshold. Ties are interpolated lineary. A `true-value` determines which label(s) is true. Curves: * ROC (Receiver Operating Characteristic) - `:fpr` and `:tpr` * PR or PrecRec (Precision-Recall) - `:recall` and `:precision` * DET (Detection Error Tradeoff) - `:fpr` and `:fnr` Returned measures contain: * `:thr` - thresholds * `:p`, `:n`, `:total` * `:tp`, `:fp`, `:fn`, `:tn` * `:tpr`/`:recall`/`:sensitivity`, `:fnr`/`:miss-rate`, `:fpr`/`:fallout`, `:tnr`/`:specificity` * `:ppv`/`:precision`, `:fdr`, `:for`, `:npv` * `:mcc` * `:f1-score` * `:kappa` * `:fm` * `:ts`/`:jaccard`
(binomial-ci number-of-successes number-of-trials)(binomial-ci number-of-successes number-of-trials method)(binomial-ci number-of-successes number-of-trials method alpha)Calculates a confidence interval for a binomial proportion.
Given the number of observed successes in a fixed number of trials, this function
estimates a confidence interval for the true underlying probability of success (p).
Different statistical methods are available for calculating the interval, as the accuracy and behavior of the interval can vary, especially for small sample sizes or probabilities close to 0 or 1.
Parameters:
number-of-successes (long): The count of successful outcomes.number-of-trials (long): The total number of independent trials.method (keyword, optional): The method used to calculate the confidence interval.
Defaults to :asymptotic.alpha (double, optional): The significance level (alpha) for the interval.
The confidence level is 1 - alpha. Defaults to 0.05 (yielding a 95% CI).Available method values:
:asymptotic: Normal approximation interval (Wald interval), based on the Central Limit Theorem. Simple but can be inaccurate for small samples or probabilities near 0 or 1.:agresti-coull: An adjustment to the asymptotic interval, adding 'pseudo-counts' to improve performance for small samples.:clopper-pearson: An exact method based on inverting binomial tests. Provides guaranteed coverage but can be overly conservative (wider than necessary).:wilson: Score interval, derived from the score test. Generally recommended as a good balance of accuracy and coverage for various sample sizes.:prop.test: Interval typically used with prop.test in R, applies a continuity correction.:cloglog: Confidence interval based on the complementary log-log transformation.:logit: Confidence interval based on the logit transformation.:probit: Confidence interval based on the probit transformation (inverse of standard normal CDF).:arcsine: Confidence interval based on the arcsine transformation.:all: Applies all available methods and returns a map where keys are method keywords and values are their respective confidence intervals (as triplets).Returns:
[lower-bound, upper-bound, estimated-p].
lower-bound (double): The lower limit of the confidence interval.upper-bound (double): The upper limit of the confidence interval.estimated-p (double): The observed proportion of successes (number-of-successes / number-of-trials).If method is :all, returns a map of results from each method.
See also binomial-test for performing a hypothesis test on a binomial proportion.
Calculates a confidence interval for a binomial proportion. Given the number of observed `successes` in a fixed number of `trials`, this function estimates a confidence interval for the true underlying probability of success (`p`). Different statistical methods are available for calculating the interval, as the accuracy and behavior of the interval can vary, especially for small sample sizes or probabilities close to 0 or 1. Parameters: - `number-of-successes` (long): The count of successful outcomes. - `number-of-trials` (long): The total number of independent trials. - `method` (keyword, optional): The method used to calculate the confidence interval. Defaults to `:asymptotic`. - `alpha` (double, optional): The significance level (alpha) for the interval. The confidence level is `1 - alpha`. Defaults to `0.05` (yielding a 95% CI). Available `method` values: - `:asymptotic`: Normal approximation interval (Wald interval), based on the Central Limit Theorem. Simple but can be inaccurate for small samples or probabilities near 0 or 1. - `:agresti-coull`: An adjustment to the asymptotic interval, adding 'pseudo-counts' to improve performance for small samples. - `:clopper-pearson`: An exact method based on inverting binomial tests. Provides guaranteed coverage but can be overly conservative (wider than necessary). - `:wilson`: Score interval, derived from the score test. Generally recommended as a good balance of accuracy and coverage for various sample sizes. - `:prop.test`: Interval typically used with `prop.test` in R, applies a continuity correction. - `:cloglog`: Confidence interval based on the complementary log-log transformation. - `:logit`: Confidence interval based on the logit transformation. - `:probit`: Confidence interval based on the probit transformation (inverse of standard normal CDF). - `:arcsine`: Confidence interval based on the arcsine transformation. - `:all`: Applies all available methods and returns a map where keys are method keywords and values are their respective confidence intervals (as triplets). Returns: - A vector `[lower-bound, upper-bound, estimated-p]`. - `lower-bound` (double): The lower limit of the confidence interval. - `upper-bound` (double): The upper limit of the confidence interval. - `estimated-p` (double): The observed proportion of successes (`number-of-successes / number-of-trials`). If `method` is `:all`, returns a map of results from each method. See also [[binomial-test]] for performing a hypothesis test on a binomial proportion.
(binomial-test xs)(binomial-test xs maybe-params)(binomial-test number-of-successes
number-of-trials
{:keys [alpha p ci-method sides]
:or {alpha 0.05 p 0.5 ci-method :asymptotic sides :two-sided}})Performs an exact test of a simple null hypothesis about the probability of success in a Bernoulli experiment, based on the binomial distribution.
This test assesses the null hypothesis that the true probability of success (p)
in the underlying population is equal to a specified value (default 0.5).
The function can be called in two ways:
(binomial-test number-of-successes number-of-trials params)(binomial-test xs params), where xs is a sequence of outcomes.
In this case, the outcomes in xs are converted to true/false based on the
:true-false-conv parameter (if provided, otherwise numeric 1s are true),
and the number of successes and total trials are derived from xs.Parameters:
number-of-successes (long): Observed number of successful outcomes.number-of-trials (long): Total number of trials.xs (sequence): Sample data (used in the alternative call signature).params (map, optional): Options map:
:p (double, default 0.5): The hypothesized probability of success under the null hypothesis.:alpha (double, default 0.05): Significance level for confidence interval calculation.:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): True probability p is not equal to the hypothesized p.:one-sided-greater: True probability p is greater than the hypothesized p.:one-sided-less: True probability p is less than the hypothesized p.:ci-method (keyword, default :asymptotic): Method used to calculate the confidence interval for the probability of success. See binomial-ci and binomial-ci-methods for available options (e.g., :wilson, :clopper-pearson).:true-false-conv (optional, used only with xs): A function, set, or map to convert elements of xs into boolean true (success) or false (failure). See binary-measures-all documentation for details. If nil and xs contains numbers, 1.0 is treated as success.Returns a map containing:
:p-value: The probability of observing a result as extreme as, or more extreme than, the observed number of successes, assuming the null hypothesis is true. Calculated using the binomial distribution.:p: The hypothesized probability of success used in the test.:successes: The observed number of successes.:trials: The total number of trials.:alpha: Significance level used for the confidence interval.:level: Confidence level (1 - alpha).:sides / :test-type: Alternative hypothesis side used.:stat: The test statistic (the observed number of successes).:estimate: The observed proportion of successes (successes / trials).:ci-method: Confidence interval method used.:confidence-interval: A confidence interval for the true probability of success, calculated using the specified :ci-method and adjusted for the :sides parameter.Performs an exact test of a simple null hypothesis about the probability of success
in a Bernoulli experiment, based on the binomial distribution.
This test assesses the null hypothesis that the true probability of success (`p`)
in the underlying population is equal to a specified value (default 0.5).
The function can be called in two ways:
1. With counts: `(binomial-test number-of-successes number-of-trials params)`
2. With data: `(binomial-test xs params)`, where `xs` is a sequence of outcomes.
In this case, the outcomes in `xs` are converted to true/false based on the
`:true-false-conv` parameter (if provided, otherwise numeric 1s are true),
and the number of successes and total trials are derived from `xs`.
Parameters:
- `number-of-successes` (long): Observed number of successful outcomes.
- `number-of-trials` (long): Total number of trials.
- `xs` (sequence): Sample data (used in the alternative call signature).
- `params` (map, optional): Options map:
- `:p` (double, default `0.5`): The hypothesized probability of success under the null hypothesis.
- `:alpha` (double, default `0.05`): Significance level for confidence interval calculation.
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): True probability `p` is not equal to the hypothesized `p`.
- `:one-sided-greater`: True probability `p` is greater than the hypothesized `p`.
- `:one-sided-less`: True probability `p` is less than the hypothesized `p`.
- `:ci-method` (keyword, default `:asymptotic`): Method used to calculate the confidence interval for the probability of success. See [[binomial-ci]] and [[binomial-ci-methods]] for available options (e.g., `:wilson`, `:clopper-pearson`).
- `:true-false-conv` (optional, used only with `xs`): A function, set, or map to convert elements of `xs` into boolean `true` (success) or `false` (failure). See [[binary-measures-all]] documentation for details. If `nil` and `xs` contains numbers, `1.0` is treated as success.
Returns a map containing:
- `:p-value`: The probability of observing a result as extreme as, or more extreme than, the observed number of successes, assuming the null hypothesis is true. Calculated using the binomial distribution.
- `:p`: The hypothesized probability of success used in the test.
- `:successes`: The observed number of successes.
- `:trials`: The total number of trials.
- `:alpha`: Significance level used for the confidence interval.
- `:level`: Confidence level (`1 - alpha`).
- `:sides` / `:test-type`: Alternative hypothesis side used.
- `:stat`: The test statistic (the observed number of successes).
- `:estimate`: The observed proportion of successes (`successes / trials`).
- `:ci-method`: Confidence interval method used.
- `:confidence-interval`: A confidence interval for the true probability of success, calculated using the specified `:ci-method` and adjusted for the `:sides` parameter.(bonett-seier-test xs)(bonett-seier-test xs params)(bonett-seier-test xs geary-kurtosis {:keys [sides] :or {sides :two-sided}})Performs the Bonett-Seier test for normality based on Geary's 'g' kurtosis measure.
This test assesses the null hypothesis that the data comes from a normally
distributed population by checking if the sample Geary's 'g' statistic
significantly deviates from the value expected under normality (sqrt(2/pi)).
Parameters:
xs (seq of numbers): The sample data. Requires (count xs) > 3 for variance calculation.geary-kurtosis (double, optional): A pre-calculated Geary's 'g' kurtosis value.
If omitted, it's calculated from xs.params (map, optional): Options map:
:sides (keyword, default :two-sided): Specifies the alternative hypothesis
regarding the deviation from normal kurtosis.
:two-sided (default): The population kurtosis (measured by 'g') is different from normal.:one-sided-greater: Population is leptokurtic ('g' < sqrt(2/pi)). Note Geary's 'g' decreases with peakedness.:one-sided-less: Population is platykurtic ('g' > sqrt(2/pi)). Note Geary's 'g' increases with flatness.Returns a map containing:
:Z: The final test statistic (approximately standard normal under H0).:stat: Alias for :Z.:p-value: The p-value associated with Z and the specified :sides.:kurtosis: The Geary's 'g' kurtosis value used in the test.:n: The sample size.:sides: The alternative hypothesis side used.References:
See also kurtosis, kurtosis-test, normality-test, jarque-bera-test.
Performs the Bonett-Seier test for normality based on Geary's 'g' kurtosis measure.
This test assesses the null hypothesis that the data comes from a normally
distributed population by checking if the sample Geary's 'g' statistic
significantly deviates from the value expected under normality (`sqrt(2/pi)`).
Parameters:
- `xs` (seq of numbers): The sample data. Requires `(count xs) > 3` for variance calculation.
- `geary-kurtosis` (double, optional): A pre-calculated Geary's 'g' kurtosis value.
If omitted, it's calculated from `xs`.
- `params` (map, optional): Options map:
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis
regarding the deviation from normal kurtosis.
- `:two-sided` (default): The population kurtosis (measured by 'g') is different from normal.
- `:one-sided-greater`: Population is leptokurtic ('g' < sqrt(2/pi)). Note Geary's 'g' decreases with peakedness.
- `:one-sided-less`: Population is platykurtic ('g' > sqrt(2/pi)). Note Geary's 'g' increases with flatness.
Returns a map containing:
- `:Z`: The final test statistic (approximately standard normal under H0).
- `:stat`: Alias for `:Z`.
- `:p-value`: The p-value associated with `Z` and the specified `:sides`.
- `:kurtosis`: The Geary's 'g' kurtosis value used in the test.
- `:n`: The sample size.
- `:sides`: The alternative hypothesis side used.
References:
- Bonett, D. G., & Seier, E. (2002). A test of normality with high uniform power.
Computational Statistics & Data Analysis, 40(3), 435-445. (Provides theoretical basis)
See also [[kurtosis]], [[kurtosis-test]], [[normality-test]], [[jarque-bera-test]].(bootstrap vs)(bootstrap vs samples)(bootstrap vs samples size)Generate set of samples of given size from provided data.
Default samples is 200, number of size defaults to sample size.
Generate set of samples of given size from provided data. Default `samples` is 200, number of `size` defaults to sample size.
(bootstrap-ci vs)(bootstrap-ci vs alpha)(bootstrap-ci vs alpha samples)(bootstrap-ci vs alpha samples stat-fn)Bootstrap method to calculate confidence interval.
Alpha defaults to 0.98, samples to 1000.
Last parameter is statistical function used to measure, default: mean.
Returns ci and statistical function value.
Bootstrap method to calculate confidence interval. Alpha defaults to 0.98, samples to 1000. Last parameter is statistical function used to measure, default: [[mean]]. Returns ci and statistical function value.
(box-cox-infer-lambda xs)(box-cox-infer-lambda xs lambda-range)(box-cox-infer-lambda xs lambda-range opts)Finds the optimal lambda (λ) parameter for the Box-Cox transformation of a dataset using the Maximum Likelihood Estimation (MLE) method.
The Box-Cox transformation is a family of power transformations often applied to positive data to make it more closely resemble a normal distribution and stabilize variance. This function estimates the lambda value that maximizes the log-likelihood function of the transformed data, assuming the transformed data is normally distributed.
Parameters:
xs (sequence of numbers): The input numerical data sequence.lambda-range (vector of two numbers, optional): A sequence [min-lambda, max-lambda] defining the closed interval within which the optimal lambda is searched. Defaults to [-3.0, 3.0].opts (map, optional): Additional options affecting the data used for the likelihood calculation. These options are passed to the internal data preparation step. Key options include:
:alpha (double, default 0.0): A constant value added to xs before estimating lambda. This is often used when xs contains zero or negative values and the standard Box-Cox (which requires positive input) is desired, or to explore transformations around a shifted location.:negative? (boolean, default false): If true, indicates that the likelihood is estimated based on the modified Box-Cox transformation (Bickel and Doksum approach) suitable for negative values. The estimation process will work with the absolute values of the data shifted by :alpha.Returns the estimated optimal lambda value as a double.
The inferred lambda value can then be used as the lambda parameter for the box-cox-transformation function to apply the actual transformation to the dataset.
See also box-cox-transformation, yeo-johnson-infer-lambda, yeo-johnson-transformation.
Finds the optimal lambda (λ) parameter for the Box-Cox transformation of a dataset using the Maximum Likelihood Estimation (MLE) method. The Box-Cox transformation is a family of power transformations often applied to positive data to make it more closely resemble a normal distribution and stabilize variance. This function estimates the lambda value that maximizes the log-likelihood function of the transformed data, assuming the transformed data is normally distributed. Parameters: - `xs` (sequence of numbers): The input numerical data sequence. - `lambda-range` (vector of two numbers, optional): A sequence `[min-lambda, max-lambda]` defining the closed interval within which the optimal lambda is searched. Defaults to `[-3.0, 3.0]`. - `opts` (map, optional): Additional options affecting the data used for the likelihood calculation. These options are passed to the internal data preparation step. Key options include: - `:alpha` (double, default 0.0): A constant value added to `xs` before estimating lambda. This is often used when `xs` contains zero or negative values and the standard Box-Cox (which requires positive input) is desired, or to explore transformations around a shifted location. - `:negative?` (boolean, default `false`): If `true`, indicates that the likelihood is estimated based on the modified Box-Cox transformation (Bickel and Doksum approach) suitable for negative values. The estimation process will work with the absolute values of the data shifted by `:alpha`. Returns the estimated optimal lambda value as a double. The inferred lambda value can then be used as the `lambda` parameter for the [[box-cox-transformation]] function to apply the actual transformation to the dataset. See also [[box-cox-transformation]], [[yeo-johnson-infer-lambda]], [[yeo-johnson-transformation]].
(box-cox-transformation xs)(box-cox-transformation xs lambda)(box-cox-transformation xs lambda {:keys [scaled? inverse?] :as opts})Applies Box-Cox transformation to a data.
The Box-Cox transformation is a family of power transformations used to stabilize variance and make data more normally distributed.
Parameters:
xs (seq of numbers): The input data.lambda (default 0.0): The power parameter. If nil or [lambda-min, lambda-max], lambda is inferred using maximum log likelihood.alpha (optional): A shift parameter applied before transformation.scaled? (default false): Scale by geometric mean or any other numbernegative? (default false): Allow negative valuesinverse? (default: false): Perform inverse operation, lambda can't be inferred.Returns transformed data.
Related: yeo-johnson-transformation
Applies Box-Cox transformation to a data. The Box-Cox transformation is a family of power transformations used to stabilize variance and make data more normally distributed. Parameters: - `xs` (seq of numbers): The input data. - `lambda` (default `0.0`): The power parameter. If `nil` or `[lambda-min, lambda-max]`, `lambda` is inferred using maximum log likelihood. - Options map: - `alpha` (optional): A shift parameter applied before transformation. - `scaled?` (default `false`): Scale by geometric mean or any other number - `negative?` (default `false`): Allow negative values - `inverse?` (default: `false`): Perform inverse operation, `lambda` can't be inferred. Returns transformed data. Related: `yeo-johnson-transformation`
(brown-forsythe-test xss)(brown-forsythe-test xss params)Brown-Forsythe test for homogeneity of variances.
This test is a modification of Levene's test, using the median instead of the mean for calculating the spread within each group. This makes the test more robust against non-normally distributed data.
Calls levene-test with :statistic set to median. Accepts the same parameters
as levene-test, except for :statistic.
Parameters:
xss (sequence of sequences): A collection of data groups.params (map, optional): Options map (see levene-test).Brown-Forsythe test for homogeneity of variances. This test is a modification of Levene's test, using the median instead of the mean for calculating the spread within each group. This makes the test more robust against non-normally distributed data. Calls [[levene-test]] with `:statistic` set to [[median]]. Accepts the same parameters as [[levene-test]], except for `:statistic`. Parameters: - `xss` (sequence of sequences): A collection of data groups. - `params` (map, optional): Options map (see [[levene-test]]).
(chisq-test contingency-table-or-xs)(chisq-test contingency-table-or-xs params)Chi square test, a power divergence test for lambda 1.0
Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Chi square test, a power divergence test for `lambda` 1.0
Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(ci vs)(ci vs alpha)Calculates the Student's t-distribution based confidence interval for the mean of vs, together with the mean itself.
The interval is built as mean ± critical-value * stddev / sqrt(n), where the critical value is the 1-alpha/2 quantile of the t-distribution with n-1 degrees of freedom (n being the sample size). This is the standard parametric confidence interval for the mean, assuming approximately normal data.
Parameters:
vs (sequence of numbers): Input data.alpha (double): Significance level, in range (0,1). Defaults to 0.05, giving a 95% confidence interval.Returns a 3-element vector [lower-bound upper-bound mean].
See also bootstrap-ci, mean, stddev, sem-extent.
Calculates the Student's t-distribution based confidence interval for the mean of `vs`, together with the mean itself. The interval is built as `mean ± critical-value * stddev / sqrt(n)`, where the critical value is the `1-alpha/2` quantile of the t-distribution with `n-1` degrees of freedom (`n` being the sample size). This is the standard parametric confidence interval for the mean, assuming approximately normal data. Parameters: - `vs` (sequence of numbers): Input data. - `alpha` (double): Significance level, in range `(0,1)`. Defaults to `0.05`, giving a 95% confidence interval. Returns a 3-element vector `[lower-bound upper-bound mean]`. See also [[bootstrap-ci]], [[mean]], [[stddev]], [[sem-extent]].
(cliffs-delta [group1 group2])(cliffs-delta group1 group2)Calculates Cliff's Delta (δ), a non-parametric effect size measure for assessing the difference between two groups of ordinal or continuous data.
Cliff's Delta quantifies the degree of overlap between two distributions. It represents the probability that a randomly chosen value from the first group is greater than a randomly chosen value from the second group, minus the reverse probability.
Parameters:
group1 (seq of numbers): The first sample.group2 (seq of numbers): The second sample.Returns the calculated Cliff's Delta value as a double.
Interpretation:
group1 is greater than every value in group2.group2 is greater than every value in group1.Cliff's Delta is a robust measure, suitable for ordinal data or when assumptions of parametric tests (like normality or equal variances) are violated. It is closely related to the wmw-odds (Wilcoxon-Mann-Whitney odds) and the ameasure (Vargha-Delaney A).
See also wmw-odds, ameasure, cohens-d, glass-delta.
Calculates Cliff's Delta (δ), a non-parametric effect size measure for assessing the difference between two groups of ordinal or continuous data. Cliff's Delta quantifies the degree of overlap between two distributions. It represents the probability that a randomly chosen value from the first group is greater than a randomly chosen value from the second group, minus the reverse probability. Parameters: - `group1` (seq of numbers): The first sample. - `group2` (seq of numbers): The second sample. Returns the calculated Cliff's Delta value as a double. Interpretation: - A value of +1 indicates complete separation where every value in `group1` is greater than every value in `group2`. - A value of -1 indicates complete separation where every value in `group2` is greater than every value in `group1`. - A value of 0 indicates complete overlap between the distributions. - Values between -1 and 1 indicate varying degrees of overlap. Cohen (1988) suggested guidelines for effect size: |δ| < 0.147 (negligible), 0.147 ≤ |δ| < 0.33 (small), 0.33 ≤ |δ| < 0.474 (medium), |δ| ≥ 0.474 (large). Cliff's Delta is a robust measure, suitable for ordinal data or when assumptions of parametric tests (like normality or equal variances) are violated. It is closely related to the [[wmw-odds]] (Wilcoxon-Mann-Whitney odds) and the [[ameasure]] (Vargha-Delaney A). See also [[wmw-odds]], [[ameasure]], [[cohens-d]], [[glass-delta]].
(coefficient-matrix vss)(coefficient-matrix vss measure-fn)(coefficient-matrix vss measure-fn symmetric?)Generates a matrix of pairwise coefficients from a sequence of sequences.
This function calculates a matrix where the element at row i and column j
is the result of applying the provided measure-fn to the i-th sequence
and the j-th sequence from the input vss.
Parameters:
vss (sequence of sequences of numbers): The collection of data sequences. Each
inner sequence is treated as a variable or set of observations. All inner
sequences should ideally have the same length if the measure-fn expects it.measure-fn (function, optional): A function of two arguments (sequences)
that returns a double representing the coefficient or measure between them.
Defaults to pearson-correlation.symmetric? (boolean, optional): If true, the function assumes that
measure-fn(a, b) is equal to measure-fn(b, a). It calculates the upper
(or lower) triangle of the matrix and mirrors the values to the other side.
This is an optimization for symmetric measures like correlation and covariance.
If false (default), all pairwise combinations (i, j) are calculated independently.Returns a sequence of sequences (a matrix) of doubles.
Note: While this function's symmetric? parameter defaults to false,
convenience functions like correlation-matrix and covariance-matrix
wrap this function and explicitly set symmetric? to true as their
respective measures are symmetric.
See also correlation-matrix, covariance-matrix.
Generates a matrix of pairwise coefficients from a sequence of sequences. This function calculates a matrix where the element at row `i` and column `j` is the result of applying the provided `measure-fn` to the `i`-th sequence and the `j`-th sequence from the input `vss`. Parameters: - `vss` (sequence of sequences of numbers): The collection of data sequences. Each inner sequence is treated as a variable or set of observations. All inner sequences should ideally have the same length if the `measure-fn` expects it. - `measure-fn` (function, optional): A function of two arguments (sequences) that returns a double representing the coefficient or measure between them. Defaults to [[pearson-correlation]]. - `symmetric?` (boolean, optional): If `true`, the function assumes that `measure-fn(a, b)` is equal to `measure-fn(b, a)`. It calculates the upper (or lower) triangle of the matrix and mirrors the values to the other side. This is an optimization for symmetric measures like correlation and covariance. If `false` (default), all pairwise combinations `(i, j)` are calculated independently. Returns a sequence of sequences (a matrix) of doubles. Note: While this function's `symmetric?` parameter defaults to `false`, convenience functions like [[correlation-matrix]] and [[covariance-matrix]] wrap this function and explicitly set `symmetric?` to `true` as their respective measures are symmetric. See also [[correlation-matrix]], [[covariance-matrix]].
(cohens-d [group1 group2])(cohens-d group1 group2)(cohens-d group1 group2 method)Calculate Cohen's d effect size between two groups.
Cohen's d is a standardized measure used to quantify the magnitude of the difference between the means of two independent groups. It expresses the mean difference in terms of standard deviation units.
The most common formula for Cohen's d is:
d = (mean(group1) - mean(group2)) / pooled_stddev
where pooled_stddev is the pooled standard deviation of the two groups,
calculated under the assumption of equal variances.
Parameters:
group1 (seq of numbers): The first independent sample.group2 (seq of numbers): The second independent sample.method (optional keyword): Specifies the method for calculating the pooled standard deviation,
affecting the denominator of the formula. Possible values are :unbiased (default),
:biased, or :avg. See pooled-stddev for details on these methods.Returns the calculated Cohen's d effect size as a double.
Interpretation guidelines (approximate for normal distributions):
Assumptions:
:method implies assumptions about equal variances (default :unbiased and :biased assume equal variances, while :avg does not but might be less standard).See also hedges-g (a version bias-corrected for small sample sizes),
glass-delta (an alternative effect size measure using the control group standard deviation),
pooled-stddev.
Calculate Cohen's d effect size between two groups.
Cohen's d is a standardized measure used to quantify the magnitude of the
difference between the means of two independent groups. It expresses the mean
difference in terms of standard deviation units.
The most common formula for Cohen's d is:
d = (mean(group1) - mean(group2)) / pooled_stddev
where `pooled_stddev` is the pooled standard deviation of the two groups,
calculated under the assumption of equal variances.
Parameters:
- `group1` (seq of numbers): The first independent sample.
- `group2` (seq of numbers): The second independent sample.
- `method` (optional keyword): Specifies the method for calculating the pooled standard deviation,
affecting the denominator of the formula. Possible values are `:unbiased` (default),
`:biased`, or `:avg`. See [[pooled-stddev]] for details on these methods.
Returns the calculated Cohen's d effect size as a double.
Interpretation guidelines (approximate for normal distributions):
- |d| = 0.2: small effect
- |d| = 0.5: medium effect
- |d| = 0.8: large effect
Assumptions:
- The two samples are independent.
- Data within each group are approximately normally distributed.
- The choice of `:method` implies assumptions about equal variances (default `:unbiased` and `:biased` assume equal variances, while `:avg` does not but might be less standard).
See also [[hedges-g]] (a version bias-corrected for small sample sizes),
[[glass-delta]] (an alternative effect size measure using the control group standard deviation),
[[pooled-stddev]].(cohens-d-corrected [group1 group2])(cohens-d-corrected group1 group2)(cohens-d-corrected group1 group2 method)Calculates Cohen's d effect size corrected for bias in small sample sizes.
This function applies a correction factor (derived from the gamma function) to
Cohen's d (cohens-d) to provide a less biased estimate of the population
effect size when sample sizes are small. This corrected measure is sometimes
referred to as Hedges' g, though this function specifically implements the
correction applied to Cohen's d.
The correction factor is (1 - 3 / (4 * df - 1)) where df is the degrees of
freedom used in the standard Cohen's d calculation.
Parameters:
group1 (seq of numbers): The first independent sample.group2 (seq of numbers): The second independent sample.method (optional keyword): Specifies the method for calculating the pooled
standard deviation, affecting the denominator of the formula (passed to
cohens-d). Possible values are :unbiased (default), :biased, or :avg.
See pooled-stddev for details on these methods.Returns the calculated bias-corrected Cohen's d effect size as a double.
Note: While this function is named cohens-d-corrected, Hedges' g (calculated
by hedges-g-corrected) also applies a similar small-sample bias correction.
Differences might exist based on the specific correction formula or degree of
freedom definition used. This function uses (count group1) + (count group2) - 2
as the degrees of freedom for the correction by default (when :unbiased method
is used for cohens-d).
See also cohens-d, hedges-g, hedges-g-corrected.
Calculates Cohen's d effect size corrected for bias in small sample sizes. This function applies a correction factor (derived from the gamma function) to Cohen's d ([[cohens-d]]) to provide a less biased estimate of the population effect size when sample sizes are small. This corrected measure is sometimes referred to as Hedges' g, though this function specifically implements the correction applied to Cohen's d. The correction factor is `(1 - 3 / (4 * df - 1))` where `df` is the degrees of freedom used in the standard Cohen's d calculation. Parameters: - `group1` (seq of numbers): The first independent sample. - `group2` (seq of numbers): The second independent sample. - `method` (optional keyword): Specifies the method for calculating the pooled standard deviation, affecting the denominator of the formula (passed to [[cohens-d]]). Possible values are `:unbiased` (default), `:biased`, or `:avg`. See [[pooled-stddev]] for details on these methods. Returns the calculated bias-corrected Cohen's d effect size as a double. Note: While this function is named `cohens-d-corrected`, Hedges' g (calculated by [[hedges-g-corrected]]) also applies a similar small-sample bias correction. Differences might exist based on the specific correction formula or degree of freedom definition used. This function uses `(count group1) + (count group2) - 2` as the degrees of freedom for the correction by default (when `:unbiased` method is used for `cohens-d`). See also [[cohens-d]], [[hedges-g]], [[hedges-g-corrected]].
(cohens-f [group1 group2])(cohens-f group1 group2)(cohens-f group1 group2 type)Calculates Cohen's f, a measure of effect size derived as the square root of Cohen's f² (cohens-f2).
Cohen's f is a standardized measure quantifying the magnitude of an effect, often used in the context of ANOVA or regression. It is the square root of the ratio of the variance explained by the effect to the unexplained variance.
Parameters:
group1 (seq of numbers): The dependent variable.group2 (seq of numbers): The independent variable (or predictor). Must have the same length as group1.type (keyword, optional): Specifies the measure of 'Proportion of Variance Explained'
used in the underlying cohens-f2 calculation. Defaults to :eta.
:eta (default): Uses Eta-squared (sample R²), a measure of variance explained in the sample.:omega: Uses Omega-squared, a less biased estimate of variance explained in the population.:epsilon: Uses Epsilon-squared, another less biased estimate of variance explained in the population.group1 and group2 and returning a double representing the proportion of variance explained.Returns the calculated Cohen's f effect size as a double. Values range from 0 upwards.
Interpretation:
group1 explained by group2).See also cohens-f2, eta-sq, omega-sq, epsilon-sq.
Calculates Cohen's f, a measure of effect size derived as the square root of Cohen's f² ([[cohens-f2]]).
Cohen's f is a standardized measure quantifying the magnitude of an effect,
often used in the context of ANOVA or regression. It is the square root of
the ratio of the variance explained by the effect to the unexplained variance.
Parameters:
- `group1` (seq of numbers): The dependent variable.
- `group2` (seq of numbers): The independent variable (or predictor). Must have the same length as `group1`.
- `type` (keyword, optional): Specifies the measure of 'Proportion of Variance Explained'
used in the underlying [[cohens-f2]] calculation. Defaults to `:eta`.
- `:eta` (default): Uses Eta-squared (sample R²), a measure of variance explained in the sample.
- `:omega`: Uses Omega-squared, a less biased estimate of variance explained in the population.
- `:epsilon`: Uses Epsilon-squared, another less biased estimate of variance explained in the population.
- Any function: A function accepting `group1` and `group2` and returning a double representing the proportion of variance explained.
Returns the calculated Cohen's f effect size as a double. Values range from 0 upwards.
Interpretation:
- Values are positive. Larger values indicate a stronger effect (more variance in `group1` explained by `group2`).
- Cohen's guidelines for interpreting the magnitude of f² (and by extension, f) are:
- $f = 0.10$ (approx. $f^2 = 0.01$): small effect
- $f = 0.25$ (approx. $f^2 = 0.0625$): medium effect
- $f = 0.40$ (approx. $f^2 = 0.16$): large effect
(Note: Guidelines are often quoted for f², interpret f as $\sqrt{f^2}$)
See also [[cohens-f2]], [[eta-sq]], [[omega-sq]], [[epsilon-sq]].(cohens-f2 [group1 group2])(cohens-f2 group1 group2)(cohens-f2 group1 group2 type)Calculates Cohen's f², a measure of effect size often used in ANOVA or regression.
Cohen's f² quantifies the magnitude of the effect of an independent variable or set of predictors on a dependent variable, expressed as the ratio of the variance explained by the effect to the unexplained variance.
This function allows calculating f² using different measures for the 'Proportion of Variance Explained',
specified by the type parameter:
:eta (default): Uses eta-sq (Eta-squared), which in this implementation is
equivalent to the sample $R^2$ from a linear regression of group1 on group2.
This is a measure of the proportion of variance explained in the sample.:omega: Uses omega-sq (Omega-squared), a less biased estimate of the
proportion of variance explained in the population.:epsilon: Uses epsilon-sq (Epsilon-squared), another less biased estimate
of the proportion of variance explained in the population, similar to adjusted $R^2$.group1 and group2 and returning a double representing the proportion of variance explained.Parameters:
group1 (seq of numbers): The dependent variable.group2 (seq of numbers): The independent variable (or predictor). Must have the same length as group1.type (keyword, optional): Specifies the measure of 'Proportion of Variance Explained' to use (:eta, :omega, :epsilon or any function). Defaults to :eta.Returns the calculated Cohen's f² effect size as a double. Values range from 0 upwards.
Interpretation Guidelines (approximate, often used for F-tests in ANOVA/regression):
See also cohens-f, eta-sq, omega-sq, epsilon-sq.
Calculates Cohen's f², a measure of effect size often used in ANOVA or regression. Cohen's f² quantifies the magnitude of the effect of an independent variable or set of predictors on a dependent variable, expressed as the ratio of the variance explained by the effect to the unexplained variance. This function allows calculating f² using different measures for the 'Proportion of Variance Explained', specified by the `type` parameter: - `:eta` (default): Uses [[eta-sq]] (Eta-squared), which in this implementation is equivalent to the sample $R^2$ from a linear regression of `group1` on `group2`. This is a measure of the proportion of variance explained in the sample. - `:omega`: Uses [[omega-sq]] (Omega-squared), a less biased estimate of the proportion of variance explained in the population. - `:epsilon`: Uses [[epsilon-sq]] (Epsilon-squared), another less biased estimate of the proportion of variance explained in the population, similar to adjusted $R^2$. - Any function: A function accepting `group1` and `group2` and returning a double representing the proportion of variance explained. Parameters: - `group1` (seq of numbers): The dependent variable. - `group2` (seq of numbers): The independent variable (or predictor). Must have the same length as `group1`. - `type` (keyword, optional): Specifies the measure of 'Proportion of Variance Explained' to use (`:eta`, `:omega`, `:epsilon` or any function). Defaults to `:eta`. Returns the calculated Cohen's f² effect size as a double. Values range from 0 upwards. Interpretation Guidelines (approximate, often used for F-tests in ANOVA/regression): - $f^2 = 0.02$: small effect - $f^2 = 0.15$: medium effect - $f^2 = 0.35$: large effect See also [[cohens-f]], [[eta-sq]], [[omega-sq]], [[epsilon-sq]].
(cohens-kappa contingency-table)(cohens-kappa group1 group2)Calculates Cohen's Kappa coefficient (κ), a statistic that measures inter-rater agreement for categorical items, while correcting for chance agreement.
It is often used to assess the consistency of agreement between two raters or methods. Its value typically ranges from -1 to +1:
κ = 1: Perfect agreement.κ = 0: Agreement is no better than chance.κ < 0: Agreement is worse than chance.The function can be called in two ways:
With two sequences group1 and group2:
The function will automatically construct a 2x2 contingency table from
the unique values in the sequences (assuming they represent two binary
variables). The mapping of values to table cells (e.g., what corresponds
to TP, TN, FP, FN) depends on how contingency-table orders the unique values.
For direct control over which cell is which, use the contingency table input.
With a contingency table: The contingency table can be provided as:
[row-index, column-index] tuples and values are counts
(e.g., {[0 0] TP, [0 1] FP, [1 0] FN, [1 1] TN}). This is the output format
of contingency-table with two inputs. The mapping of indices to TP/TN/FP/FN
depends on the order of unique values in the original data if generated by
contingency-table, or the explicit structure if created manually or via
rows->contingency-table. Standard convention maps [0 0] to TP, [0 1] to FP,
[1 0] to FN, and [1 1] to TN for binary outcomes.[[TP FP] [FN TN]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of binary outcomes/categories.group2 (sequence): The second sequence of binary outcomes/categories.
Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed 2x2 contingency table.
The cell values should represent counts (e.g., TP, FN, FP, TN).Returns the calculated Cohen's Kappa coefficient as a double.
See also weighted-kappa (for ordinal data with partial agreement), contingency-table, contingency-2x2-measures, binary-measures-all.
Calculates Cohen's Kappa coefficient (κ), a statistic that measures inter-rater
agreement for categorical items, while correcting for chance agreement.
It is often used to assess the consistency of agreement between two raters or
methods. Its value typically ranges from -1 to +1:
- `κ = 1`: Perfect agreement.
- `κ = 0`: Agreement is no better than chance.
- `κ < 0`: Agreement is worse than chance.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a 2x2 contingency table from
the unique values in the sequences (assuming they represent two binary
variables). The mapping of values to table cells (e.g., what corresponds
to TP, TN, FP, FN) depends on how `contingency-table` orders the unique values.
For direct control over which cell is which, use the contingency table input.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] TP, [0 1] FP, [1 0] FN, [1 1] TN}`). This is the output format
of [[contingency-table]] with two inputs. The mapping of indices to TP/TN/FP/FN
depends on the order of unique values in the original data if generated by
[[contingency-table]], or the explicit structure if created manually or via
[[rows->contingency-table]]. Standard convention maps `[0 0]` to TP, `[0 1]` to FP,
`[1 0]` to FN, and `[1 1]` to TN for binary outcomes.
- A sequence of sequences representing the rows of the table
(e.g., `[[TP FP] [FN TN]]`). This is equivalent to [[rows->contingency-table]].
Parameters:
- `group1` (sequence): The first sequence of binary outcomes/categories.
- `group2` (sequence): The second sequence of binary outcomes/categories.
Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed 2x2 contingency table.
The cell values should represent counts (e.g., TP, FN, FP, TN).
Returns the calculated Cohen's Kappa coefficient as a double.
See also [[weighted-kappa]] (for ordinal data with partial agreement), [[contingency-table]], [[contingency-2x2-measures]], [[binary-measures-all]].(cohens-q r1 r2)(cohens-q group1 group2a group2b)(cohens-q group1a group2a group1b group2b)Compares two correlation coefficients by calculating the difference between their Fisher z-transformations.
The Fisher z-transformation (atanh) of a correlation coefficient r helps normalize the sampling distribution of correlation coefficients. The difference between two z'-transformed correlations is often used as a test statistic.
The function supports comparing correlations in different scenarios via its arities:
(cohens-q r1 r2): Calculates the difference between the Fisher z-transformations of two correlation values r1 and r2 provided directly. This is typically used when comparing two independent correlation coefficients (e.g., correlations from two separate studies). Returns atanh(r1) - atanh(r2).
r1, r2 (double): Correlation coefficient values (-1.0 to 1.0).(cohens-q group1 group2a group2b): Calculates the difference between the correlation of group1 with group2a and the correlation of group1 with group2b. This is commonly used for comparing dependent correlations (where group1 is a common variable). Calculates atanh(pearson-correlation(group1, group2a)) - atanh(pearson-correlation(group1, group2b)).
group1, group2a, group2b (sequences): Data sequences from which Pearson correlations are computed.(cohens-q group1a group2a group1b group2b): Calculates the difference between the correlation of group1a with group2a and the correlation of group1b with group2b. This is typically used for comparing two independent correlations obtained from two distinct pairs of variables (all four sequences are independent). Calculates atanh(pearson-correlation(group1a, group2a)) - atanh(pearson-correlation(group1b, group2b)).
group1a, group2a, group1b, group2b (sequences): Data sequences from which Pearson correlations are computed.Returns the difference between the Fisher z-transformed correlation values as a double.
Note: For comparing dependent correlations (3-arity case), standard statistical tests (e.g., Steiger's test) are more complex than a simple difference of z-transforms and involve the correlation between group2a and group2b. This function provides the basic difference value.
Compares two correlation coefficients by calculating the difference between their Fisher z-transformations. The Fisher z-transformation (`atanh`) of a correlation coefficient `r` helps normalize the sampling distribution of correlation coefficients. The difference between two z'-transformed correlations is often used as a test statistic. The function supports comparing correlations in different scenarios via its arities: - `(cohens-q r1 r2)`: Calculates the difference between the Fisher z-transformations of two correlation values `r1` and `r2` provided directly. This is typically used when comparing two *independent* correlation coefficients (e.g., correlations from two separate studies). Returns `atanh(r1) - atanh(r2)`. - `r1`, `r2` (double): Correlation coefficient values (-1.0 to 1.0). - `(cohens-q group1 group2a group2b)`: Calculates the difference between the correlation of `group1` with `group2a` and the correlation of `group1` with `group2b`. This is commonly used for comparing *dependent* correlations (where `group1` is a common variable). Calculates `atanh(pearson-correlation(group1, group2a)) - atanh(pearson-correlation(group1, group2b))`. - `group1`, `group2a`, `group2b` (sequences): Data sequences from which Pearson correlations are computed. - `(cohens-q group1a group2a group1b group2b)`: Calculates the difference between the correlation of `group1a` with `group2a` and the correlation of `group1b` with `group2b`. This is typically used for comparing two *independent* correlations obtained from two distinct pairs of variables (all four sequences are independent). Calculates `atanh(pearson-correlation(group1a, group2a)) - atanh(pearson-correlation(group1b, group2b))`. - `group1a`, `group2a`, `group1b`, `group2b` (sequences): Data sequences from which Pearson correlations are computed. Returns the difference between the Fisher z-transformed correlation values as a double. Note: For comparing dependent correlations (3-arity case), standard statistical tests (e.g., Steiger's test) are more complex than a simple difference of z-transforms and involve the correlation between `group2a` and `group2b`. This function provides the basic difference value.
(cohens-u1 [group1 group2])(cohens-u1 group1 group2)Calculates a non-parametric measure of difference or separation between two samples.
This function computes a value derived from cohens-u2, which internally
quantifies a minimal difference between corresponding quantiles of the two
empirical distributions.
Parameters:
group1 (seq of numbers): The first sample.group2 (seq of numbers): The second sample.Returns the calculated measure as a double, in the range [0, 1] (since
cohens-u2 itself is restricted to [0.5, 1]).
Interpretation:
This measure is symmetric, meaning the order of group1 and group2 does not
affect the result. It is a non-parametric measure applicable to any data samples.
See also cohens-u2 (the measure this calculation is based on),
cohens-u3 (related non-parametric measure), cohens-u1-normal
(the version applicable to normal data).
Calculates a non-parametric measure of difference or separation between two samples. This function computes a value derived from [[cohens-u2]], which internally quantifies a minimal difference between corresponding quantiles of the two empirical distributions. Parameters: - `group1` (seq of numbers): The first sample. - `group2` (seq of numbers): The second sample. Returns the calculated measure as a double, in the range [0, 1] (since [[cohens-u2]] itself is restricted to [0.5, 1]). Interpretation: - A value of 0 indicates maximum overlap (the two distributions are identical). - A value of 1 indicates complete separation (no overlap between the distributions). - Values in between indicate intermediate degrees of separation. This measure is symmetric, meaning the order of `group1` and `group2` does not affect the result. It is a non-parametric measure applicable to any data samples. See also [[cohens-u2]] (the measure this calculation is based on), [[cohens-u3]] (related non-parametric measure), [[cohens-u1-normal]] (the version applicable to normal data).
(cohens-u1-normal d)(cohens-u1-normal group1 group2)(cohens-u1-normal group1 group2 method)Calculates Cohen's U1, a measure of non-overlap between two distributions assumed to be normal with equal variances.
Cohen's U1 quantifies the proportion of scores in the lower-scoring group that overlap with the scores in the higher-scoring group. A U1 of 0 means no overlap, while a U1 of 1 means complete overlap (distributions are identical).
This measure is calculated directly from Cohen's d statistic (cohens-d) assuming
normal distributions and equal variances.
Parameters:
group1 (seq of numbers): The first sample.group2 (seq of numbers): The second sample.method (optional keyword): Specifies the method for calculating the pooled standard deviation
used in the underlying cohens-d calculation. Possible values are :unbiased (default),
:biased, or :avg. See pooled-stddev for details.d (double): A pre-calculated Cohen's d value. If provided, group1, group2, and method are ignored.Returns the calculated Cohen's U1 as a double [0, 1].
Assumptions:
See also cohens-d, cohens-u2-normal, cohens-u3-normal, p-overlap (a non-parametric overlap measure).
Calculates Cohen's U1, a measure of non-overlap between two distributions assumed to be normal with equal variances. Cohen's U1 quantifies the proportion of scores in the lower-scoring group that overlap with the scores in the higher-scoring group. A U1 of 0 means no overlap, while a U1 of 1 means complete overlap (distributions are identical). This measure is calculated directly from Cohen's d statistic ([[cohens-d]]) assuming normal distributions and equal variances. Parameters: - `group1` (seq of numbers): The first sample. - `group2` (seq of numbers): The second sample. - `method` (optional keyword): Specifies the method for calculating the pooled standard deviation used in the underlying [[cohens-d]] calculation. Possible values are `:unbiased` (default), `:biased`, or `:avg`. See [[pooled-stddev]] for details. - `d` (double): A pre-calculated Cohen's d value. If provided, `group1`, `group2`, and `method` are ignored. Returns the calculated Cohen's U1 as a double [0, 1]. Assumptions: - Both samples are drawn from normally distributed populations. - The populations have equal variances (homoscedasticity). See also [[cohens-d]], [[cohens-u2-normal]], [[cohens-u3-normal]], [[p-overlap]] (a non-parametric overlap measure).
(cohens-u2 [group1 group2])(cohens-u2 group1 group2)Calculates a measure of overlap between two samples, referred to as Cohen's U2.
This function quantifies the degree to which the distributions of group1 and group2 overlap. It is related to comparing values at corresponding percentile levels across the two groups or the proportion of values in one group that are below the median of the other. A value of 0 indicates no overlap, while a value of 1 indicates complete overlap (distributions are identical).
The measure is symmetric, meaning (cohens-u2 group1 group2) is equal to (cohens-u2 group2 group1).
This is a non-parametric measure, suitable for any data samples, and does not assume normality, unlike cohens-u2-normal.
Parameters:
group1, group2 (sequences): The two samples directly as arguments.Returns the calculated Cohen's U2 value as a double. The value typically ranges from 0 to 1. A value closer to 0.5 indicates substantial overlap between the distributions (e.g., the median of one group is near the median of the other); values closer to 0 or 1 indicate less overlap (greater separation between the distributions).
Implementation note: the underlying objective (a function of the two samples' empirical, step-function quantiles) is piecewise-constant with jumps only at each sample's empirical cumulative-probability breakpoints, so it is generally non-unimodal. The true global minimum is found by an exact search over that finite breakpoint set, rather than by a continuous bracketing optimizer (which can converge to a non-global local minimum on this kind of objective).
Calculates a measure of overlap between two samples, referred to as Cohen's U2. This function quantifies the degree to which the distributions of `group1` and `group2` overlap. It is related to comparing values at corresponding percentile levels across the two groups or the proportion of values in one group that are below the median of the other. A value of 0 indicates no overlap, while a value of 1 indicates complete overlap (distributions are identical). The measure is symmetric, meaning `(cohens-u2 group1 group2)` is equal to `(cohens-u2 group2 group1)`. This is a non-parametric measure, suitable for any data samples, and does not assume normality, unlike [[cohens-u2-normal]]. Parameters: - `group1`, `group2` (sequences): The two samples directly as arguments. Returns the calculated Cohen's U2 value as a double. The value typically ranges from 0 to 1. A value closer to 0.5 indicates substantial overlap between the distributions (e.g., the median of one group is near the median of the other); values closer to 0 or 1 indicate less overlap (greater separation between the distributions). Implementation note: the underlying objective (a function of the two samples' empirical, step-function quantiles) is piecewise-constant with jumps only at each sample's empirical cumulative-probability breakpoints, so it is generally non-unimodal. The true global minimum is found by an exact search over that finite breakpoint set, rather than by a continuous bracketing optimizer (which can converge to a non-global local minimum on this kind of objective).
(cohens-u2-normal d)(cohens-u2-normal group1 group2)(cohens-u2-normal group1 group2 method)Calculates Cohen's U2, a measure of overlap between two distributions assumed to be normal with equal variances.
Cohen's U2 quantifies the proportion of scores in the lower-scoring group that are below the point located halfway between the means of the two groups (or equivalently, the proportion of scores in the higher-scoring group that are above this halfway point). This measure is calculated from Cohen's d statistic (cohens-d) using the standard normal cumulative distribution function ($\Phi$): $\Phi(0.5 |d|)$.
Parameters:
group1 (seq of numbers): The first sample.group2 (seq of numbers): The second sample.method (optional keyword): Specifies the method for calculating the pooled standard deviation used in the underlying cohens-d calculation. Possible values are :unbiased (default), :biased, or :avg. See pooled-stddev for details.d (double): A pre-calculated Cohen's d value. If provided, group1, group2, and method are ignored.Returns the calculated Cohen's U2 as a double [0.0, 1.0]. A value closer to 0.5 indicates greater overlap between the distributions; values closer to 0 or 1 indicate less overlap.
Assumptions:
See also cohens-d, cohens-u1-normal, cohens-u3-normal, p-overlap (a non-parametric overlap measure).
Calculates Cohen's U2, a measure of overlap between two distributions assumed to be normal with equal variances. Cohen's U2 quantifies the proportion of scores in the lower-scoring group that are below the point located halfway between the means of the two groups (or equivalently, the proportion of scores in the higher-scoring group that are above this halfway point). This measure is calculated from Cohen's d statistic ([[cohens-d]]) using the standard normal cumulative distribution function ($\Phi$): $\Phi(0.5 |d|)$. Parameters: - `group1` (seq of numbers): The first sample. - `group2` (seq of numbers): The second sample. - `method` (optional keyword): Specifies the method for calculating the pooled standard deviation used in the underlying [[cohens-d]] calculation. Possible values are `:unbiased` (default), `:biased`, or `:avg`. See [[pooled-stddev]] for details. - `d` (double): A pre-calculated Cohen's d value. If provided, `group1`, `group2`, and `method` are ignored. Returns the calculated Cohen's U2 as a double [0.0, 1.0]. A value closer to 0.5 indicates greater overlap between the distributions; values closer to 0 or 1 indicate less overlap. Assumptions: - Both samples are drawn from normally distributed populations. - The populations have equal variances (homoscedasticity). See also [[cohens-d]], [[cohens-u1-normal]], [[cohens-u3-normal]], [[p-overlap]] (a non-parametric overlap measure).
(cohens-u3 [group1 group2])(cohens-u3 group1 group2)(cohens-u3 group1 group2 estimation-strategy)Calculates Cohen's U3 for two samples.
In this implementation, Cohen's U3 is defined as the proportion of values
in the second sample (group2) that are less than the median of the first
sample (group1).
Parameters:
group1 (seq of numbers): The first sample. The median of this sample is used as the threshold.group2 (seq of numbers): The second sample. Values from this sample are counted if they fall below the median of group1.estimation-strategy (optional keyword): The strategy used to estimate the median of group1.
Defaults to :legacy. See median or quantile for available strategies
(e.g., :r1 through :r9).Returns the calculated proportion as a double between 0.0 and 1.0.
Interpretation:
group2 are greater than or equal to the median of group1.group2 are below the median of group1.group2 are less than the median of group1.Note: This measure is not symmetric. (cohens-u3 group1 group2) is generally
not equal to (cohens-u3 group2 group1).
This is a non-parametric measure, suitable for any data samples, and does not
assume normality, unlike cohens-u3-normal.
See also cohens-u3-normal (the version applicable to normal data), cohens-u2
(a related symmetric non-parametric measure), median, quantile.
Calculates Cohen's U3 for two samples. In this implementation, Cohen's U3 is defined as the proportion of values in the second sample (`group2`) that are less than the median of the first sample (`group1`). Parameters: - `group1` (seq of numbers): The first sample. The median of this sample is used as the threshold. - `group2` (seq of numbers): The second sample. Values from this sample are counted if they fall below the median of `group1`. - `estimation-strategy` (optional keyword): The strategy used to estimate the median of `group1`. Defaults to `:legacy`. See [[median]] or [[quantile]] for available strategies (e.g., `:r1` through `:r9`). Returns the calculated proportion as a double between 0.0 and 1.0. Interpretation: - A value close to 0 means most values in `group2` are greater than or equal to the median of `group1`. - A value close to 0.5 means approximately half the values in `group2` are below the median of `group1`. - A value close to 1 means most values in `group2` are less than the median of `group1`. Note: This measure is **not symmetric**. `(cohens-u3 group1 group2)` is generally not equal to `(cohens-u3 group2 group1)`. This is a non-parametric measure, suitable for any data samples, and does not assume normality, unlike [[cohens-u3-normal]]. See also [[cohens-u3-normal]] (the version applicable to normal data), [[cohens-u2]] (a related symmetric non-parametric measure), [[median]], [[quantile]].
(cohens-u3-normal d)(cohens-u3-normal group1 group2)(cohens-u3-normal group1 group2 method)Calculates Cohen's U3, a measure of overlap between two distributions assumed to be normal with equal variances.
Cohen's U3 quantifies the proportion of scores in the lower-scoring group that fall
below the mean of the higher-scoring group. It is calculated from Cohen's d statistic
(cohens-d) using the standard normal cumulative distribution function ($\Phi$):
U3 = Φ(d).
The measure is asymmetric: U3(group1, group2) is not necessarily equal to
U3(group2, group1). The interpretation depends on which group is considered
the 'higher-scoring' one based on the sign of d. By convention, the result
often represents the proportion of the first group (group1) that is below the
mean of the second group (group2) if d is negative, or the proportion of the
second group (group2) that is below the mean of the first group (group1) if d is positive.
Parameters:
group1 (seq of numbers): The first sample.group2 (seq of numbers): The second sample.method (optional keyword): Specifies the method for calculating the pooled standard deviation
used in the underlying cohens-d calculation. Possible values are :unbiased (default),
:biased, or :avg. See pooled-stddev for details.d (double): A pre-calculated Cohen's d value. If provided, group1, group2, and method are ignored.Returns the calculated Cohen's U3 as a double [0.0, 1.0]. A value close to 0.5 suggests significant overlap. Values closer to 0 or 1 suggest less overlap (greater separation between the means).
Assumptions:
See also cohens-d, cohens-u1-normal, cohens-u2-normal, p-overlap (a non-parametric overlap measure).
Calculates Cohen's U3, a measure of overlap between two distributions assumed to be normal with equal variances. Cohen's U3 quantifies the proportion of scores in the lower-scoring group that fall below the mean of the higher-scoring group. It is calculated from Cohen's d statistic ([[cohens-d]]) using the standard normal cumulative distribution function ($\Phi$): `U3 = Φ(d)`. The measure is asymmetric: `U3(group1, group2)` is not necessarily equal to `U3(group2, group1)`. The interpretation depends on which group is considered the 'higher-scoring' one based on the sign of d. By convention, the result often represents the proportion of the *first* group (`group1`) that is below the mean of the *second* group (`group2`) if d is negative, or the proportion of the *second* group (`group2`) that is below the mean of the *first* group (`group1`) if d is positive. Parameters: - `group1` (seq of numbers): The first sample. - `group2` (seq of numbers): The second sample. - `method` (optional keyword): Specifies the method for calculating the pooled standard deviation used in the underlying [[cohens-d]] calculation. Possible values are `:unbiased` (default), `:biased`, or `:avg`. See [[pooled-stddev]] for details. - `d` (double): A pre-calculated Cohen's d value. If provided, `group1`, `group2`, and `method` are ignored. Returns the calculated Cohen's U3 as a double [0.0, 1.0]. A value close to 0.5 suggests significant overlap. Values closer to 0 or 1 suggest less overlap (greater separation between the means). Assumptions: - Both samples are drawn from normally distributed populations. - The populations have equal variances (homoscedasticity). See also [[cohens-d]], [[cohens-u1-normal]], [[cohens-u2-normal]], [[p-overlap]] (a non-parametric overlap measure).
(cohens-w contingency-table)(cohens-w group1 group2)Calculates Cohen's W effect size for the association between two nominal variables represented in a contingency table.
Cohen's W is a measure of association derived from the Pearson's Chi-squared statistic. It quantifies the magnitude of the difference between the observed frequencies and the frequencies expected under the assumption of independence between the variables.
Its value ranges from 0 upwards:
The function can be called in two ways:
group1 and group2:
The function will automatically construct a contingency table from
the unique values in the sequences.[row-index, column-index] tuples and values are counts
(e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This is the output format
of contingency-table with two inputs.[[10 5] [3 12]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of categorical data.group2 (sequence): The second sequence of categorical data. Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed contingency table.Returns the calculated Cohen's W coefficient as a double.
See also chisq-test, cramers-v, cramers-c, tschuprows-t, contingency-table.
Calculates Cohen's W effect size for the association between two nominal
variables represented in a contingency table.
Cohen's W is a measure of association derived from the Pearson's Chi-squared
statistic. It quantifies the magnitude of the difference between the observed
frequencies and the frequencies expected under the assumption of independence
between the variables.
Its value ranges from 0 upwards:
- A value of 0 indicates no association between the variables.
- Larger values indicate a stronger association.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a contingency table from
the unique values in the sequences.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This is the output format
of [[contingency-table]] with two inputs.
- A sequence of sequences representing the rows of the table
(e.g., `[[10 5] [3 12]]`). This is equivalent to [[rows->contingency-table]].
Parameters:
- `group1` (sequence): The first sequence of categorical data.
- `group2` (sequence): The second sequence of categorical data. Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed contingency table.
Returns the calculated Cohen's W coefficient as a double.
See also [[chisq-test]], [[cramers-v]], [[cramers-c]], [[tschuprows-t]], [[contingency-table]].(confusion-matrix confusion-mat)(confusion-matrix actual prediction)(confusion-matrix actual prediction encode-true)(confusion-matrix tp fn fp tn)Creates a 2x2 confusion matrix for binary classification.
A confusion matrix summarizes the results of a binary classification problem, showing the counts of True Positives (TP), False Positives (FP), False Negatives (FN), and True Negatives (TN).
TP: Actual is True, Predicted is True FP: Actual is False, Predicted is True (Type I error) FN: Actual is True, Predicted is False (Type II error) TN: Actual is False, Predicted is False
The function supports several input formats:
(confusion-matrix tp fn fp tn): Direct input of the four counts.
tp (long): True Positive count.fn (long): False Negative count.fp (long): False Positive count.tn (long): True Negative count.(confusion-matrix confusion-matrix-representation): Input as a structured representation.
confusion-matrix-representation: Can be:
:tp, :fn, :fp, :tn (e.g., {:tp 10 :fn 2 :fp 5 :tn 80}).[[TP FP] [FN TN]] (e.g., [[10 5] [2 80]]).[TP FN FP TN] (e.g., [10 2 5 80]).(confusion-matrix actual prediction): Input as two sequences of outcomes.
actual (sequence): Sequence of true outcomes.prediction (sequence): Sequence of predicted outcomes. Must have the same length as actual.
Values in actual and prediction are compared element-wise. By default,
any non-nil or non-zero value is treated as true, and nil or 0.0 is
treated as false.(confusion-matrix actual prediction encode-true): Input as two sequences with a specified encoding for true.
actual, prediction: Sequences as in the previous arity.encode-true: Specifies how values in actual and prediction are converted to boolean true or false.
nil (default): Non-nil/non-zero is true.false, the value is false.true if the value satisfies the predicate.Returns a map with keys :tp, :fn, :fp, and :tn representing the counts.
This function is commonly used to prepare input for binary classification
metrics like those provided by binary-measures-all and binary-measures.
Creates a 2x2 confusion matrix for binary classification.
A confusion matrix summarizes the results of a binary classification problem, showing
the counts of True Positives (TP), False Positives (FP), False Negatives (FN),
and True Negatives (TN).
TP: Actual is True, Predicted is True
FP: Actual is False, Predicted is True (Type I error)
FN: Actual is True, Predicted is False (Type II error)
TN: Actual is False, Predicted is False
The function supports several input formats:
1. `(confusion-matrix tp fn fp tn)`: Direct input of the four counts.
- `tp` (long): True Positive count.
- `fn` (long): False Negative count.
- `fp` (long): False Positive count.
- `tn` (long): True Negative count.
2. `(confusion-matrix confusion-matrix-representation)`: Input as a structured representation.
- `confusion-matrix-representation`: Can be:
- A map with keys like `:tp`, `:fn`, `:fp`, `:tn` (e.g., `{:tp 10 :fn 2 :fp 5 :tn 80}`).
- A sequence of sequences representing rows `[[TP FP] [FN TN]]` (e.g., `[[10 5] [2 80]]`).
- A flat sequence `[TP FN FP TN]` (e.g., `[10 2 5 80]`).
3. `(confusion-matrix actual prediction)`: Input as two sequences of outcomes.
- `actual` (sequence): Sequence of true outcomes.
- `prediction` (sequence): Sequence of predicted outcomes. Must have the same length as `actual`.
Values in `actual` and `prediction` are compared element-wise. By default,
any non-`nil` or non-zero value is treated as `true`, and `nil` or `0.0` is
treated as `false`.
4. `(confusion-matrix actual prediction encode-true)`: Input as two sequences with a specified encoding for `true`.
- `actual`, `prediction`: Sequences as in the previous arity.
- `encode-true`: Specifies how values in `actual` and `prediction` are converted to boolean `true` or `false`.
- `nil` (default): Non-`nil`/non-zero is true.
- Any sequence/set: Values found in this collection are true.
- A map: Values are mapped according to the map; if a key is not found or maps to `false`, the value is false.
- A predicate function: Returns `true` if the value satisfies the predicate.
Returns a map with keys `:tp`, `:fn`, `:fp`, and `:tn` representing the counts.
This function is commonly used to prepare input for binary classification
metrics like those provided by [[binary-measures-all]] and [[binary-measures]].(contingency-2x2-measures & args)Calculates a subset of common statistics and measures for a 2x2 contingency table.
This function provides a selection of the most frequently used measures from the
more comprehensive contingency-2x2-measures-all.
The function accepts the same input formats as contingency-2x2-measures-all:
(contingency-2x2-measures a b c d): Takes the four counts as arguments.(contingency-2x2-measures [a b c d]): Takes a sequence of the four counts.(contingency-2x2-measures [[a b] [c d]]): Takes a sequence of sequences representing the rows.(contingency-2x2-measures {:a a :b b :c c :d d}): Takes a map of counts (accepts :a/:b/:c/:d keys).Parameters:
a, b, c, d (long): Counts in the 2x2 table cells.map-or-seq (map or sequence): A representation of the 2x2 table.Returns a map containing a selection of measures:
:OR: Odds Ratio (Odds Ratio):chi2: Pearson's Chi-squared statistic:yates: Yates' continuity corrected Chi-squared statistic:cochran-mantel-haenszel: Cochran-Mantel-Haenszel statistic:cohens-kappa: Cohen's Kappa coefficient:yules-q: Yule's Q measure of association:holley-guilfords-g: Holley-Guilford's G measure:huberts-gamma: Hubert's Gamma measure:yules-y: Yule's Y measure of association:cramers-v: Cramer's V measure of association:phi: Phi coefficient (Matthews Correlation Coefficient):scotts-pi: Scott's Pi measure of agreement:cohens-h: Cohen's H measure:PCC: Pearson's Contingency Coefficient:PCC-adjusted: Adjusted Pearson's Contingency Coefficient:TCC: Tschuprow's Contingency Coefficient:F1: F1 Score:bangdiwalas-b: Bangdiwala's B statistic:mcnemars-chi2: McNemar's Chi-squared test statistic:gwets-ac1: Gwet's AC1 measureFor a more comprehensive set of 2x2 measures and their detailed descriptions, see contingency-2x2-measures-all.
Calculates a subset of common statistics and measures for a 2x2 contingency table.
This function provides a selection of the most frequently used measures from the
more comprehensive [[contingency-2x2-measures-all]].
The function accepts the same input formats as [[contingency-2x2-measures-all]]:
1. `(contingency-2x2-measures a b c d)`: Takes the four counts as arguments.
2. `(contingency-2x2-measures [a b c d])`: Takes a sequence of the four counts.
3. `(contingency-2x2-measures [[a b] [c d]])`: Takes a sequence of sequences representing the rows.
4. `(contingency-2x2-measures {:a a :b b :c c :d d})`: Takes a map of counts (accepts `:a/:b/:c/:d` keys).
Parameters:
- `a, b, c, d` (long): Counts in the 2x2 table cells.
- `map-or-seq` (map or sequence): A representation of the 2x2 table.
Returns a map containing a selection of measures:
- `:OR`: Odds Ratio (Odds Ratio)
- `:chi2`: Pearson's Chi-squared statistic
- `:yates`: Yates' continuity corrected Chi-squared statistic
- `:cochran-mantel-haenszel`: Cochran-Mantel-Haenszel statistic
- `:cohens-kappa`: Cohen's Kappa coefficient
- `:yules-q`: Yule's Q measure of association
- `:holley-guilfords-g`: Holley-Guilford's G measure
- `:huberts-gamma`: Hubert's Gamma measure
- `:yules-y`: Yule's Y measure of association
- `:cramers-v`: Cramer's V measure of association
- `:phi`: Phi coefficient (Matthews Correlation Coefficient)
- `:scotts-pi`: Scott's Pi measure of agreement
- `:cohens-h`: Cohen's H measure
- `:PCC`: Pearson's Contingency Coefficient
- `:PCC-adjusted`: Adjusted Pearson's Contingency Coefficient
- `:TCC`: Tschuprow's Contingency Coefficient
- `:F1`: F1 Score
- `:bangdiwalas-b`: Bangdiwala's B statistic
- `:mcnemars-chi2`: McNemar's Chi-squared test statistic
- `:gwets-ac1`: Gwet's AC1 measure
For a more comprehensive set of 2x2 measures and their detailed descriptions, see [[contingency-2x2-measures-all]].(contingency-2x2-measures-all map-or-seq)(contingency-2x2-measures-all [a b] [c d])(contingency-2x2-measures-all a b c d)Calculates a comprehensive set of statistics and measures for a 2x2 contingency table.
A 2x2 contingency table cross-tabulates two categorical variables, each with two levels. The table counts are typically represented as:
+---+---+ | a | b | +---+---+ | c | d | +---+---+
Where a, b, c, d are the counts in the respective cells.
This function calculates numerous measures, including:
The function can be called with the four counts directly or with a representation of the contingency table:
(contingency-2x2-measures-all a b c d): Takes the four counts as arguments.(contingency-2x2-measures-all [a b c d]): Takes a sequence of the four counts.(contingency-2x2-measures-all [[a b] [c d]]): Takes a sequence of sequences representing the rows.(contingency-2x2-measures-all {:a a :b b :c c :d d}): Takes a map of counts (accepts :a/:b/:c/:d keys).Parameters:
a (long): Count in the top-left cell.b (long): Count in the top-right cell.c (long): Count in the bottom-left cell.d (long): Count in the bottom-right cell.map-or-seq (map or sequence): A representation of the 2x2 table as described above.Returns a map containing a wide range of calculated statistics. Keys include:
:n, :table, :expected, :marginals, :proportions, :p-values (map), :OR, :lOR, :RR, :risk (map), :SE, :measures (map).
See also contingency-2x2-measures for a selected subset of these measures,
mcc for the Matthews Correlation Coefficient (Phi), and binary-measures-all
for metrics derived from a confusion matrix (often a 2x2 table in binary classification).
Calculates a comprehensive set of statistics and measures for a 2x2 contingency table.
A 2x2 contingency table cross-tabulates two categorical variables, each with two levels.
The table counts are typically represented as:
+---+---+
| a | b |
+---+---+
| c | d |
+---+---+
Where `a, b, c, d` are the counts in the respective cells.
This function calculates numerous measures, including:
* Chi-squared statistics (Pearson, Yates' corrected, CMH) and their p-values.
* Measures of association (Phi, Yule's Q, Holley-Guilford's G, Hubert's Gamma, Yule's Y, Cramer's V, Scott's Pi, Cohen's H, Pearson/Tschuprow's CC).
* Measures of agreement (Cohen's Kappa).
* Risk and effect size measures (Odds Ratio (OR), Relative Risk (RR), Risk Difference (RD), NNT, etc.).
* Table marginals and proportions.
The function can be called with the four counts directly or with a representation
of the contingency table:
1. `(contingency-2x2-measures-all a b c d)`: Takes the four counts as arguments.
2. `(contingency-2x2-measures-all [a b c d])`: Takes a sequence of the four counts.
3. `(contingency-2x2-measures-all [[a b] [c d]])`: Takes a sequence of sequences representing the rows.
4. `(contingency-2x2-measures-all {:a a :b b :c c :d d})`: Takes a map of counts (accepts `:a/:b/:c/:d` keys).
Parameters:
- `a` (long): Count in the top-left cell.
- `b` (long): Count in the top-right cell.
- `c` (long): Count in the bottom-left cell.
- `d` (long): Count in the bottom-right cell.
- `map-or-seq` (map or sequence): A representation of the 2x2 table as described above.
Returns a map containing a wide range of calculated statistics. Keys include:
`:n`, `:table`, `:expected`, `:marginals`, `:proportions`, `:p-values` (map), `:OR`, `:lOR`, `:RR`, `:risk` (map), `:SE`, `:measures` (map).
See also [[contingency-2x2-measures]] for a selected subset of these measures,
[[mcc]] for the Matthews Correlation Coefficient (Phi), and [[binary-measures-all]]
for metrics derived from a confusion matrix (often a 2x2 table in binary classification).(contingency-table & seqs)Creates a frequency map (contingency table) from one or more sequences.
If one sequence xs is provided, it returns a simple frequency map of the values
in xs.
If multiple sequences s1, s2, ..., sn are provided, it creates a contingency table
of the tuples formed by the corresponding elements [s1_i, s2_i, ..., sn_i] at
each index i. The returned map keys are these tuples, and values are their
frequencies.
Parameters:
seqs (one or more sequences): The input sequences. All sequences should ideally
have the same length, as elements are paired by index.Returns a map where keys represent unique combinations of values (or single values if only one sequence is input) and values are the counts of these combinations.
See also rows->contingency-table, contingency-table->marginals.
Creates a frequency map (contingency table) from one or more sequences. If one sequence `xs` is provided, it returns a simple frequency map of the values in `xs`. If multiple sequences `s1, s2, ..., sn` are provided, it creates a contingency table of the tuples formed by the corresponding elements `[s1_i, s2_i, ..., sn_i]` at each index `i`. The returned map keys are these tuples, and values are their frequencies. Parameters: - `seqs` (one or more sequences): The input sequences. All sequences should ideally have the same length, as elements are paired by index. Returns a map where keys represent unique combinations of values (or single values if only one sequence is input) and values are the counts of these combinations. See also [[rows->contingency-table]], [[contingency-table->marginals]].
(contingency-table->marginals ct)Calculates marginal sums (row and column totals) and the grand total from a contingency table.
A contingency table represents the frequency distribution of observations for two or more categorical variables. This function summarizes these frequencies along the rows and columns.
The function accepts two main input formats for the contingency table:
[row-index, column-index] tuples and values are counts (e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This format is produced by contingency-table when given multiple sequences or by rows->contingency-table.[[10 5] [3 12]]). The function internally converts this format to the map format.Parameters:
ct (map or sequence of sequences): The contingency table input.Returns a map containing:
:rows: A sequence of [row-index, row-total] pairs.:cols: A sequence of [column-index, column-total] pairs.:n: The grand total of all counts in the table.:diag: A sequence of [[index, index], count] pairs for cells on the diagonal
(where row index equals column index). This is useful for square tables like
confusion matrices.See also contingency-table, rows->contingency-table.
Calculates marginal sums (row and column totals) and the grand total from a contingency table.
A contingency table represents the frequency distribution of observations for two or
more categorical variables. This function summarizes these frequencies along the
rows and columns.
The function accepts two main input formats for the contingency table:
1. A map where keys are `[row-index, column-index]` tuples and values are counts (e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This format is produced by [[contingency-table]] when given multiple sequences or by [[rows->contingency-table]].
2. A sequence of sequences representing the rows of the table, where each inner sequence contains counts for the columns in that row (e.g., `[[10 5] [3 12]]`). The function internally converts this format to the map format.
Parameters:
- `ct` (map or sequence of sequences): The contingency table input.
Returns a map containing:
- `:rows`: A sequence of `[row-index, row-total]` pairs.
- `:cols`: A sequence of `[column-index, column-total]` pairs.
- `:n`: The grand total of all counts in the table.
- `:diag`: A sequence of `[[index, index], count]` pairs for cells on the diagonal
(where row index equals column index). This is useful for square tables like
confusion matrices.
See also [[contingency-table]], [[rows->contingency-table]].(correlation [vs1 vs2])(correlation vs1 vs2)Calculates the correlation coefficient between two sequences.
By default, this function calculates the Pearson product-moment correlation coefficient, which measures the linear relationship between two datasets.
This function handles the standard deviation normalization based on whether
the inputs vs1 and vs2 are treated as samples or populations (it uses
sample standard deviation derived from variance).
Parameters:
[vs1 vs2] (sequence of two sequences): A sequence containing the two sequences of numbers.vs1, vs2 (sequences): The two sequences of numbers directly as arguments.Both sequences must have the same length.
Returns the calculated correlation coefficient (a value between -1.0 and 1.0) as a double.
Returns NaN if one or both sequences have zero variance (are constant).
See also covariance, pearson-correlation, spearman-correlation, kendall-correlation, correlation-matrix.
Calculates the correlation coefficient between two sequences. By default, this function calculates the Pearson product-moment correlation coefficient, which measures the linear relationship between two datasets. This function handles the standard deviation normalization based on whether the inputs `vs1` and `vs2` are treated as samples or populations (it uses sample standard deviation derived from [[variance]]). Parameters: - `[vs1 vs2]` (sequence of two sequences): A sequence containing the two sequences of numbers. - `vs1`, `vs2` (sequences): The two sequences of numbers directly as arguments. Both sequences must have the same length. Returns the calculated correlation coefficient (a value between -1.0 and 1.0) as a double. Returns `NaN` if one or both sequences have zero variance (are constant). See also [[covariance]], [[pearson-correlation]], [[spearman-correlation]], [[kendall-correlation]], [[correlation-matrix]].
(correlation-matrix vss)(correlation-matrix vss measure)Generates a matrix of pairwise correlation coefficients from a sequence of sequences.
Given a collection of data sequences vss, where each inner sequence represents
a variable, this function calculates a square matrix where the element at row i
and column j is the correlation coefficient between the i-th and j-th
sequences in vss.
Parameters:
vss (sequence of sequences of numbers): The collection of data sequences.
Each inner sequence is treated as a variable. All inner sequences must have the same length.measure (keyword, optional): Specifies the type of correlation coefficient to calculate.
Defaults to :pearson.
:pearson (default): Calculates the Pearson product-moment correlation coefficient.:kendall: Calculates Kendall's Tau rank correlation coefficient.:spearman: Calculates Spearman's rank correlation coefficient.Returns a sequence of sequences (a matrix) of doubles representing the correlation matrix. The matrix is symmetric, as correlation is a symmetric measure.
See also pearson-correlation, spearman-correlation, kendall-correlation,
covariance-matrix, coefficient-matrix.
Generates a matrix of pairwise correlation coefficients from a sequence of sequences. Given a collection of data sequences `vss`, where each inner sequence represents a variable, this function calculates a square matrix where the element at row `i` and column `j` is the correlation coefficient between the `i`-th and `j`-th sequences in `vss`. Parameters: - `vss` (sequence of sequences of numbers): The collection of data sequences. Each inner sequence is treated as a variable. All inner sequences must have the same length. - `measure` (keyword, optional): Specifies the type of correlation coefficient to calculate. Defaults to `:pearson`. - `:pearson` (default): Calculates the Pearson product-moment correlation coefficient. - `:kendall`: Calculates Kendall's Tau rank correlation coefficient. - `:spearman`: Calculates Spearman's rank correlation coefficient. Returns a sequence of sequences (a matrix) of doubles representing the correlation matrix. The matrix is symmetric, as correlation is a symmetric measure. See also [[pearson-correlation]], [[spearman-correlation]], [[kendall-correlation]], [[covariance-matrix]], [[coefficient-matrix]].
(count= [vs1 vs2-or-val])(count= vs1 vs2-or-val)Count equal values in both seqs. Same as L0
Calculates the number of pairs of corresponding elements that are equal between two sequences, or between a sequence and a single scalar value.
Parameters:
vs1 (sequence of numbers): The first sequence.vs2-or-val (sequence of numbers or single number): The second sequence of
numbers, or a single number to compare against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the count of equal elements as a long integer.
Count equal values in both seqs. Same as [[L0]] Calculates the number of pairs of corresponding elements that are equal between two sequences, or between a sequence and a single scalar value. Parameters: - `vs1` (sequence of numbers): The first sequence. - `vs2-or-val` (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the count of equal elements as a long integer.
(covariance [vs1 vs2])(covariance vs1 vs2)Covariance of two sequences.
This function calculates the sample covariance.
Parameters:
[vs1 vs2] (sequence of two sequences): A sequence containing the two sequences of numbers.vs1, vs2 (sequences): The two sequences of numbers directly as arguments.Both sequences must have the same length.
Returns the calculated sample covariance as a double.
See also correlation, covariance-matrix.
Covariance of two sequences. This function calculates the *sample* covariance. Parameters: - `[vs1 vs2]` (sequence of two sequences): A sequence containing the two sequences of numbers. - `vs1`, `vs2` (sequences): The two sequences of numbers directly as arguments. Both sequences must have the same length. Returns the calculated sample covariance as a double. See also [[correlation]], [[covariance-matrix]].
(covariance-matrix vss)Generates a matrix of pairwise covariance coefficients from a sequence of sequences.
Given a collection of data sequences vss, where each inner sequence represents
a variable, this function calculates a square matrix where the element at row i
and column j is the sample covariance between the i-th and j-th sequences
in vss.
Parameters:
vss (sequence of sequences of numbers): The collection of data sequences.
Each inner sequence is treated as a variable. All inner sequences must have the same length.Returns a sequence of sequences (a matrix) of doubles representing the covariance matrix. The matrix is symmetric, as covariance is a symmetric measure ($Cov(X,Y) = Cov(Y,X)$).
Internally uses coefficient-matrix with the covariance function and symmetric? set to true.
See also covariance, correlation-matrix, coefficient-matrix.
Generates a matrix of pairwise covariance coefficients from a sequence of sequences. Given a collection of data sequences `vss`, where each inner sequence represents a variable, this function calculates a square matrix where the element at row `i` and column `j` is the sample covariance between the `i`-th and `j`-th sequences in `vss`. Parameters: - `vss` (sequence of sequences of numbers): The collection of data sequences. Each inner sequence is treated as a variable. All inner sequences must have the same length. Returns a sequence of sequences (a matrix) of doubles representing the covariance matrix. The matrix is symmetric, as covariance is a symmetric measure ($Cov(X,Y) = Cov(Y,X)$). Internally uses [[coefficient-matrix]] with the [[covariance]] function and `symmetric?` set to `true`. See also [[covariance]], [[correlation-matrix]], [[coefficient-matrix]].
(cramers-c contingency-table)(cramers-c group1 group2)Calculates Cramer's C, a measure of association (effect size) between two nominal variables represented in a contingency table.
Its value ranges from 0 to 1, where 0 indicates no association and 1 indicates a perfect association. It is particularly useful for tables larger than 2x2.
The function can be called in two ways:
group1 and group2:
The function will automatically construct a contingency table from
the unique values in the sequences.[row-index, column-index] tuples and values are counts
(e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This is the output format
of contingency-table with two inputs.[[10 5] [3 12]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of categorical data.group2 (sequence): The second sequence of categorical data. Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed contingency table.Returns the calculated Cramer's C coefficient as a double.
See also chisq-test, cramers-v, cohens-w, tschuprows-t, contingency-table.
Calculates Cramer's C, a measure of association (effect size) between two
nominal variables represented in a contingency table.
Its value ranges from 0 to 1, where 0 indicates no association and 1 indicates
a perfect association. It is particularly useful for tables larger than 2x2.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a contingency table from
the unique values in the sequences.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This is the output format
of [[contingency-table]] with two inputs.
- A sequence of sequences representing the rows of the table
(e.g., `[[10 5] [3 12]]`). This is equivalent to `rows->contingency-table`.
Parameters:
- `group1` (sequence): The first sequence of categorical data.
- `group2` (sequence): The second sequence of categorical data. Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed contingency table.
Returns the calculated Cramer's C coefficient as a double.
See also [[chisq-test]], [[cramers-v]], [[cohens-w]], [[tschuprows-t]], [[contingency-table]].(cramers-v contingency-table)(cramers-v group1 group2)Calculates Cramer's V, a measure of association (effect size) between two nominal variables represented in a contingency table.
Its value ranges from 0 to 1, where 0 indicates no association and 1 indicates a perfect association. It is related to the Pearson's Chi-squared statistic and is useful for tables of any size.
The function can be called in two ways:
group1 and group2:
The function will automatically construct a contingency table from
the unique values in the sequences.[row-index, column-index] tuples and values are counts
(e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This is the output format
of contingency-table with two inputs.[[10 5] [3 12]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of categorical data.group2 (sequence): The second sequence of categorical data. Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed contingency table.Returns the calculated Cramer's V coefficient as a double.
See also chisq-test, cramers-c, cohens-w, tschuprows-t, contingency-table.
Calculates Cramer's V, a measure of association (effect size) between two
nominal variables represented in a contingency table.
Its value ranges from 0 to 1, where 0 indicates no association and 1 indicates
a perfect association. It is related to the Pearson's Chi-squared statistic
and is useful for tables of any size.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a contingency table from
the unique values in the sequences.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This is the output format
of [[contingency-table]] with two inputs.
- A sequence of sequences representing the rows of the table
(e.g., `[[10 5] [3 12]]`). This is equivalent to `rows->contingency-table`.
Parameters:
- `group1` (sequence): The first sequence of categorical data.
- `group2` (sequence): The second sequence of categorical data. Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed contingency table.
Returns the calculated Cramer's V coefficient as a double.
See also [[chisq-test]], [[cramers-c]], [[cohens-w]], [[tschuprows-t]], [[contingency-table]].(cramers-v-corrected contingency-table)(cramers-v-corrected group1 group2)Calculates the corrected Cramer's V, a measure of association (effect size) between two nominal variables represented in a contingency table, with a correction to reduce bias, particularly for small sample sizes or tables with many cells having small expected counts.
Like the uncorrected Cramer's V (cramers-v), its value ranges from 0 to 1,
where 0 indicates no association and 1 indicates a perfect association. The
correction tends to yield a value closer to the true population value in
biased situations.
The function can be called in two ways:
group1 and group2:
The function will automatically construct a contingency table from
the unique values in the sequences.[row-index, column-index] tuples and values are counts
(e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This is the output format
of contingency-table with two inputs.[[10 5] [3 12]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of categorical data.group2 (sequence): The second sequence of categorical data. Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed contingency table.Returns the calculated corrected Cramer's V coefficient as a double.
See also chisq-test, cramers-v (uncorrected), cramers-c, cohens-w,
tschuprows-t, contingency-table.
Calculates the **corrected Cramer's V**, a measure of association (effect size)
between two nominal variables represented in a contingency table, with a correction
to reduce bias, particularly for small sample sizes or tables with many cells
having small expected counts.
Like the uncorrected Cramer's V ([[cramers-v]]), its value ranges from 0 to 1,
where 0 indicates no association and 1 indicates a perfect association. The
correction tends to yield a value closer to the true population value in
biased situations.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a contingency table from
the unique values in the sequences.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This is the output format
of [[contingency-table]] with two inputs.
- A sequence of sequences representing the rows of the table
(e.g., `[[10 5] [3 12]]`). This is equivalent to [[rows->contingency-table]].
Parameters:
- `group1` (sequence): The first sequence of categorical data.
- `group2` (sequence): The second sequence of categorical data. Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed contingency table.
Returns the calculated corrected Cramer's V coefficient as a double.
See also [[chisq-test]], [[cramers-v]] (uncorrected), [[cramers-c]], [[cohens-w]],
[[tschuprows-t]], [[contingency-table]].(cressie-read-test contingency-table-or-xs)(cressie-read-test contingency-table-or-xs params)Cressie-Read test, a power divergence test for lambda 2/3
Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Cressie-Read test, a power divergence test for `lambda` 2/3
Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(cvm-statistic xs distribution)(cvm-statistic xs distribution {:keys [sorted?]})Calculates the Cramer-von Mises statistic of a sample against a distribution.
The statistic W2 measures the squared distance between the empirical cumulative distribution function of xs and the cumulative distribution function of distribution: W2 = 1 / (12 n) + sum_i (F(x_(i)) - (2 i - 1) / (2 n))^2 over the sorted observations. It returns the statistic only, without a p-value, so it is suitable as an objective for fitting a distribution or for ranking candidate distributions.
Parameters:
xs (sequence of numbers): The sample.distribution: A fastmath.random distribution.opts (map, optional):
:sorted? (boolean, default false): Set to true when xs is already sorted ascending, to skip sorting.Returns the statistic as a double, non-negative. Throws ex-info for empty xs. The result is NaN when the cumulative distribution function returns NaN.
For discrete and mixed distributions the statistic is still computed from the cumulative distribution function, but it is only descriptive.
See also ks-statistic, ad-statistic, cvm-test-one-sample.
Calculates the Cramer-von Mises statistic of a sample against a distribution. The statistic `W2` measures the squared distance between the empirical cumulative distribution function of `xs` and the cumulative distribution function of `distribution`: `W2 = 1 / (12 n) + sum_i (F(x_(i)) - (2 i - 1) / (2 n))^2` over the sorted observations. It returns the statistic only, without a p-value, so it is suitable as an objective for fitting a distribution or for ranking candidate distributions. Parameters: - `xs` (sequence of numbers): The sample. - `distribution`: A `fastmath.random` distribution. - `opts` (map, optional): - `:sorted?` (boolean, default `false`): Set to `true` when `xs` is already sorted ascending, to skip sorting. Returns the statistic as a double, non-negative. Throws `ex-info` for empty `xs`. The result is `NaN` when the cumulative distribution function returns `NaN`. For discrete and mixed distributions the statistic is still computed from the cumulative distribution function, but it is only descriptive. See also [[ks-statistic]], [[ad-statistic]], [[cvm-test-one-sample]].
(cvm-test-one-sample xs)(cvm-test-one-sample xs distribution-or-ys)(cvm-test-one-sample xs
distribution-or-ys
{:keys [sides kernel bandwidth]
:or {sides :right kernel :gaussian}})Performs the Cramer-von Mises (CvM) test for goodness-of-fit.
This test assesses the null hypothesis that a sample xs comes from a specified theoretical distribution or another empirical distribution. It uses the squared distance between the empirical and the theoretical cumulative distribution functions, which makes it more sensitive to differences along the whole range than the Kolmogorov-Smirnov test, and less focused on the tails than the Anderson-Darling test.
Parameters:
xs (seq of numbers): The sample data to be tested.distribution-or-ys (optional):
fastmath.random distribution object to test against. If omitted, defaults to the standard normal distribution (fastmath.random/default-normal).ys). In this case, an empirical distribution is estimated from ys using Kernel Density Estimation (KDE) or an enumerated distribution (see :kernel option).opts (map, optional): Options map:
:sides (keyword, default :right): Specifies the side(s) of the statistic's distribution used for the p-value.
:right (default): Tests if the observed statistic is significantly large (indicating poor fit).:left: Tests if the observed statistic is significantly small.:two-sided: Tests if the observed statistic is extreme in either tail.:kernel (keyword, default :gaussian): Used only when distribution-or-ys is a sequence. :gaussian (or other KDE kernels) uses Kernel Density Estimation, :enumerated creates a discrete empirical distribution from ys.:bandwidth (double, optional): Bandwidth for KDE (if applicable).Returns a map containing:
:W2: The Cramer-von Mises statistic, see cvm-statistic.:stat: Alias for :W2.:p-value: The p-value associated with the statistic and the specified :sides.:n: Sample size of xs.:mean: Mean of the sample xs (for context).:stddev: Standard deviation of the sample xs (for context).:sides: The alternative hypothesis side used for the p-value.The p-value uses the finite-sample distribution of the statistic for the sample size n, so it differs slightly from the asymptotic p-value (for example by about 1e-3 at n equal to 5 against the value of R goftest::cvm.test, and by about 1e-5 at n equal to 30). The parameters of the tested distribution are treated as known: when they are estimated from xs, the p-value is too large.
See also cvm-statistic, ad-test-one-sample, ks-test-one-sample.
Performs the Cramer-von Mises (CvM) test for goodness-of-fit.
This test assesses the null hypothesis that a sample `xs` comes from a specified theoretical distribution or another empirical distribution. It uses the squared distance between the empirical and the theoretical cumulative distribution functions, which makes it more sensitive to differences along the whole range than the Kolmogorov-Smirnov test, and less focused on the tails than the Anderson-Darling test.
Parameters:
- `xs` (seq of numbers): The sample data to be tested.
- `distribution-or-ys` (optional):
- A `fastmath.random` distribution object to test against. If omitted, defaults to the standard normal distribution (`fastmath.random/default-normal`).
- A sequence of numbers (`ys`). In this case, an empirical distribution is estimated from `ys` using Kernel Density Estimation (KDE) or an enumerated distribution (see `:kernel` option).
- `opts` (map, optional): Options map:
- `:sides` (keyword, default `:right`): Specifies the side(s) of the statistic's distribution used for the p-value.
- `:right` (default): Tests if the observed statistic is significantly large (indicating poor fit).
- `:left`: Tests if the observed statistic is significantly small.
- `:two-sided`: Tests if the observed statistic is extreme in either tail.
- `:kernel` (keyword, default `:gaussian`): Used only when `distribution-or-ys` is a sequence. `:gaussian` (or other KDE kernels) uses Kernel Density Estimation, `:enumerated` creates a discrete empirical distribution from `ys`.
- `:bandwidth` (double, optional): Bandwidth for KDE (if applicable).
Returns a map containing:
- `:W2`: The Cramer-von Mises statistic, see [[cvm-statistic]].
- `:stat`: Alias for `:W2`.
- `:p-value`: The p-value associated with the statistic and the specified `:sides`.
- `:n`: Sample size of `xs`.
- `:mean`: Mean of the sample `xs` (for context).
- `:stddev`: Standard deviation of the sample `xs` (for context).
- `:sides`: The alternative hypothesis side used for the p-value.
The p-value uses the finite-sample distribution of the statistic for the sample size `n`, so it differs slightly from the asymptotic p-value (for example by about `1e-3` at `n` equal to 5 against the value of R `goftest::cvm.test`, and by about `1e-5` at `n` equal to 30). The parameters of the tested distribution are treated as known: when they are estimated from `xs`, the p-value is too large.
See also [[cvm-statistic]], [[ad-test-one-sample]], [[ks-test-one-sample]].(demean vs)Subtracts the mean of vs from each of its values, centering the data around 0.
Parameters:
vs (sequence of numbers): Input data.Returns a lazy sequence of the same length as vs, with mean 0.
See also standardize, mean.
Subtracts the mean of `vs` from each of its values, centering the data around `0`. Parameters: - `vs` (sequence of numbers): Input data. Returns a lazy sequence of the same length as `vs`, with mean `0`. See also [[standardize]], [[mean]].
(dissimilarity method P-observed Q-expected)(dissimilarity method
P-observed
Q-expected
{:keys [bins probabilities? epsilon log-base power remove-zeros?]
:or
{probabilities? true epsilon 1.0E-6 log-base m/E power 2.0}})Calculates a dissimilarity (distance) measure between two probability density functions, P-observed and Q-expected, given as histograms, frequencies, probabilities, or raw data.
If Q-expected is a distribution object, a histogram is built from P-observed and compared against it directly. If :bins is set (and Q-expected is not a distribution), both P-observed and Q-expected are treated as raw data and turned into a matching pair of histograms.
Parameters:
method (keyword): Dissimilarity method to use, see below.P-observed (sequence of numbers): Frequencies, probabilities, or raw data.Q-expected (sequence of numbers, or distribution object): Frequencies, probabilities, raw data, or a distribution object to compare P-observed against.opts (map, optional):
:probabilities? (boolean): Whether P-observed/Q-expected are normalized to probabilities (summing to 1) before computing the distance. Defaults to true.:bins (long or keyword): Number of bins, or a bin-count estimation method, used to turn raw P-observed/Q-expected data into histograms, see histogram and estimate-bins.:remove-zeros? (boolean): Whether to drop paired entries where either P-observed or Q-expected is zero before computing the distance. Defaults to false.:epsilon (double): Small number substituted for 0.0 wherever a division or logarithm would otherwise be undefined. Defaults to 1.0e-6.:log-base (double): Base of the logarithm used by log-based methods. Defaults to e.:power (double): Exponent used by the :minkowski method. Defaults to 2.0.method is one of: :euclidean, :city-block, :manhattan, :chebyshev, :minkowski, :sorensen, :gower, :soergel, :kulczynski, :canberra, :lorentzian, :non-intersection, :wave-hedges, :czekanowski, :motyka, :tanimoto, :jaccard, :dice, :bhattacharyya, :hellinger, :matusita, :squared-chord, :euclidean-sq, :squared-euclidean, :pearson-chisq, :chisq, :neyman-chisq, :squared-chisq, :symmetric-chisq, :divergence, :clark, :additive-symmetric-chisq, :kullback-leibler, :jeffreys, :k-divergence, :topsoe, :jensen-shannon, :jensen-difference, :taneja, :kumar-johnson, :avg (the mean of the :city-block and :chebyshev distances).
Returns the calculated dissimilarity as a double.
Definitions for the individual methods are given in the Comprehensive Survey on Distance/Similarity Measures between Probability Density Functions by Sung-Hyuk Cha.
See also similarity, histogram, estimate-bins.
Calculates a dissimilarity (distance) measure between two probability density functions, `P-observed` and `Q-expected`, given as histograms, frequencies, probabilities, or raw data. If `Q-expected` is a distribution object, a histogram is built from `P-observed` and compared against it directly. If `:bins` is set (and `Q-expected` is not a distribution), both `P-observed` and `Q-expected` are treated as raw data and turned into a matching pair of histograms. Parameters: - `method` (keyword): Dissimilarity method to use, see below. - `P-observed` (sequence of numbers): Frequencies, probabilities, or raw data. - `Q-expected` (sequence of numbers, or distribution object): Frequencies, probabilities, raw data, or a distribution object to compare `P-observed` against. - `opts` (map, optional): - `:probabilities?` (boolean): Whether `P-observed`/`Q-expected` are normalized to probabilities (summing to `1`) before computing the distance. Defaults to `true`. - `:bins` (long or keyword): Number of bins, or a bin-count estimation method, used to turn raw `P-observed`/`Q-expected` data into histograms, see [[histogram]] and [[estimate-bins]]. - `:remove-zeros?` (boolean): Whether to drop paired entries where either `P-observed` or `Q-expected` is zero before computing the distance. Defaults to `false`. - `:epsilon` (double): Small number substituted for `0.0` wherever a division or logarithm would otherwise be undefined. Defaults to `1.0e-6`. - `:log-base` (double): Base of the logarithm used by log-based methods. Defaults to `e`. - `:power` (double): Exponent used by the `:minkowski` method. Defaults to `2.0`. `method` is one of: `:euclidean`, `:city-block`, `:manhattan`, `:chebyshev`, `:minkowski`, `:sorensen`, `:gower`, `:soergel`, `:kulczynski`, `:canberra`, `:lorentzian`, `:non-intersection`, `:wave-hedges`, `:czekanowski`, `:motyka`, `:tanimoto`, `:jaccard`, `:dice`, `:bhattacharyya`, `:hellinger`, `:matusita`, `:squared-chord`, `:euclidean-sq`, `:squared-euclidean`, `:pearson-chisq`, `:chisq`, `:neyman-chisq`, `:squared-chisq`, `:symmetric-chisq`, `:divergence`, `:clark`, `:additive-symmetric-chisq`, `:kullback-leibler`, `:jeffreys`, `:k-divergence`, `:topsoe`, `:jensen-shannon`, `:jensen-difference`, `:taneja`, `:kumar-johnson`, `:avg` (the mean of the `:city-block` and `:chebyshev` distances). Returns the calculated dissimilarity as a double. Definitions for the individual methods are given in the Comprehensive Survey on Distance/Similarity Measures between Probability Density Functions by Sung-Hyuk Cha. See also [[similarity]], [[histogram]], [[estimate-bins]].
(durbin-watson rs)Calculates the Durbin-Watson statistic (d) for a sequence of residuals.
This statistic is used to test for the presence of serial correlation, especially first-order (lag-1) autocorrelation, in the residuals from a regression analysis. Autocorrelation violates the assumption of independent errors.
Parameters:
rs (sequence of numbers): The sequence of residuals from a regression model.
The sequence should represent observations ordered by time or sequence index.Returns the calculated Durbin-Watson statistic as a double. The value ranges from 0 to 4.
Interpretation:
Calculates the Durbin-Watson statistic (d) for a sequence of residuals. This statistic is used to test for the presence of serial correlation, especially first-order (lag-1) autocorrelation, in the residuals from a regression analysis. Autocorrelation violates the assumption of independent errors. Parameters: - `rs` (sequence of numbers): The sequence of residuals from a regression model. The sequence should represent observations ordered by time or sequence index. Returns the calculated Durbin-Watson statistic as a double. The value ranges from 0 to 4. Interpretation: - Values near 2 suggest no first-order autocorrelation. - Values less than 2 suggest positive autocorrelation (residuals tend to be followed by residuals of the same sign). - Values greater than 2 suggest negative autocorrelation (residuals tend to be followed by residuals of the opposite sign).
(entropy xs)(entropy xs log-base)Calculates the Shannon entropy H(X) of the empirical distribution of a sequence of values.
Entropy quantifies the average amount of information, surprise, or uncertainty inherent in the possible outcomes of xs. It is maximal when all observed categories are equally frequent, and 0.0 when only a single category occurs.
Parameters:
xs (sequence, or map): A sequence of (typically categorical, but any hashable) observations, or a pre-computed frequency/probability map from value to count or probability (such as the output of contingency-table applied to a single sequence).log-base (double, optional): The logarithm base used. Defaults to e (Euler's number), giving entropy in nats. Use 2.0 for entropy in bits, or 10.0 for hartleys/dits.Returns the calculated Shannon entropy as a double, always >= 0.0.
See also joint-entropy, mutual-information, theils-u, contingency-table.
Calculates the Shannon entropy H(X) of the empirical distribution of a sequence of values. Entropy quantifies the average amount of information, surprise, or uncertainty inherent in the possible outcomes of `xs`. It is maximal when all observed categories are equally frequent, and `0.0` when only a single category occurs. Parameters: - `xs` (sequence, or map): A sequence of (typically categorical, but any hashable) observations, or a pre-computed frequency/probability map from value to count or probability (such as the output of [[contingency-table]] applied to a single sequence). - `log-base` (double, optional): The logarithm base used. Defaults to `e` (Euler's number), giving entropy in nats. Use `2.0` for entropy in bits, or `10.0` for hartleys/dits. Returns the calculated Shannon entropy as a double, always `>= 0.0`. See also [[joint-entropy]], [[mutual-information]], [[theils-u]], [[contingency-table]].
(epsilon-sq [group1 group2])(epsilon-sq group1 group2)Calculates Epsilon squared (ε²), an effect size measure for the simple linear regression of group1 on group2.
Epsilon squared estimates the proportion of variance in the dependent variable (group1)
that is accounted for by the independent variable (group2) in the population. It is
considered a less biased alternative to the sample R-squared (r2-determination).
The calculation is based on the sums of squares from the simple linear regression of
group1 on group2.
Parameters:
group1 (seq of numbers): The dependent variable.group2 (seq of numbers): The independent variable. Must have the same length as group1.Returns the calculated Epsilon squared value as a double. The value typically ranges from 0.0 to 1.0.
Interpretation:
group2 explains none of the variance in group1 in the population.group2 perfectly explains the variance in group1 in the population.Note: While often presented in the context of ANOVA, this implementation applies the formula to the sums of squares obtained from a simple linear regression between the two sequences.
See also eta-sq (Eta-squared, often based on $R^2$), omega-sq (another adjusted
R²-like measure), r2-determination (R-squared).
Calculates Epsilon squared (ε²), an effect size measure for the simple linear regression of `group1` on `group2`. Epsilon squared estimates the proportion of variance in the dependent variable (`group1`) that is accounted for by the independent variable (`group2`) in the population. It is considered a less biased alternative to the sample R-squared ([[r2-determination]]). The calculation is based on the sums of squares from the simple linear regression of `group1` on `group2`. Parameters: - `group1` (seq of numbers): The dependent variable. - `group2` (seq of numbers): The independent variable. Must have the same length as `group1`. Returns the calculated Epsilon squared value as a double. The value typically ranges from 0.0 to 1.0. Interpretation: - 0.0 indicates that `group2` explains none of the variance in `group1` in the population. - 1.0 indicates that `group2` perfectly explains the variance in `group1` in the population. Note: While often presented in the context of ANOVA, this implementation applies the formula to the sums of squares obtained from a simple linear regression between the two sequences. See also [[eta-sq]] (Eta-squared, often based on $R^2$), [[omega-sq]] (another adjusted R²-like measure), [[r2-determination]] (R-squared).
(estimate-bins vs)(estimate-bins vs bins-or-estimate-method)(estimate-bins vs bins-or-estimate-method opts)Estimates a suitable number of bins for a histogram of vs.
Several standard rules of thumb are available, balancing resolution against noise: some rely only on sample size, while others also take the spread or shape of the data into account.
Parameters:
vs (sequence of numbers): Input data.bins-or-estimate-method (keyword or long): Estimation method to use, or an explicit bin count. Defaults to :freedman-diaconis. One of:
:sqrt: ceil(sqrt(n)), depends only on sample size, the simplest of the estimators.:sturges: ceil(log2(n)) + 1, assumes roughly normal data, tends to undersmooth for large or non-normal samples.:rice: ceil(2 * cbrt(n)), depends only on sample size.:terrell-scott: ceil(cbrt(2 * n)), depends only on sample size, an asymptotically minimal-risk rule related to :rice.:doane: a refinement of Sturges' rule that accounts for the sample skewness (see skewness), better suited for non-normal data.:scott: bin width 3.5 * stddev / cbrt(n), assumes roughly normal data.:freedman-diaconis (default): bin width 2 * IQR / cbrt(n) (see iqr), robust to outliers.:cross-validation: the bin count minimizing the leave-one-out cross-validation estimate of the integrated squared error (Rudemo 1982, stone in numpy), adapts to the shape of the data, see fastmath.stats.bins/cross-validation-bins.:shimazaki-shinomoto: the bin count minimizing the cost of Shimazaki and Shinomoto (2007), adapts to the shape of the data, see fastmath.stats.bins/shimazaki-shinomoto-bins.long: used directly as the number of bins, bypassing estimation.opts (map, optional): options of :cross-validation and :shimazaki-shinomoto, :candidates (the number of candidate bin counts, default 200) and :shifts (the number of bin origins the cost is averaged over, default 1).The data-driven methods (:cross-validation, :shimazaki-shinomoto) pass over the data once per candidate and vary more from sample to sample than the rules of thumb. For discretized data their bin count is limited to the range divided by twice the smallest gap between values.
Returns the estimated number of bins as a long, never higher than the number of samples in vs.
See also histogram.
Estimates a suitable number of bins for a histogram of `vs`. Several standard rules of thumb are available, balancing resolution against noise: some rely only on sample size, while others also take the spread or shape of the data into account. Parameters: - `vs` (sequence of numbers): Input data. - `bins-or-estimate-method` (keyword or long): Estimation method to use, or an explicit bin count. Defaults to `:freedman-diaconis`. One of: - `:sqrt`: `ceil(sqrt(n))`, depends only on sample size, the simplest of the estimators. - `:sturges`: `ceil(log2(n)) + 1`, assumes roughly normal data, tends to undersmooth for large or non-normal samples. - `:rice`: `ceil(2 * cbrt(n))`, depends only on sample size. - `:terrell-scott`: `ceil(cbrt(2 * n))`, depends only on sample size, an asymptotically minimal-risk rule related to `:rice`. - `:doane`: a refinement of Sturges' rule that accounts for the sample skewness (see [[skewness]]), better suited for non-normal data. - `:scott`: bin width `3.5 * stddev / cbrt(n)`, assumes roughly normal data. - `:freedman-diaconis` (default): bin width `2 * IQR / cbrt(n)` (see [[iqr]]), robust to outliers. - `:cross-validation`: the bin count minimizing the leave-one-out cross-validation estimate of the integrated squared error (Rudemo 1982, `stone` in numpy), adapts to the shape of the data, see [[fastmath.stats.bins/cross-validation-bins]]. - `:shimazaki-shinomoto`: the bin count minimizing the cost of Shimazaki and Shinomoto (2007), adapts to the shape of the data, see [[fastmath.stats.bins/shimazaki-shinomoto-bins]]. - a `long`: used directly as the number of bins, bypassing estimation. - `opts` (map, optional): options of `:cross-validation` and `:shimazaki-shinomoto`, `:candidates` (the number of candidate bin counts, default `200`) and `:shifts` (the number of bin origins the cost is averaged over, default `1`). The data-driven methods (`:cross-validation`, `:shimazaki-shinomoto`) pass over the data once per candidate and vary more from sample to sample than the rules of thumb. For discretized data their bin count is limited to the range divided by twice the smallest gap between values. Returns the estimated number of bins as a long, never higher than the number of samples in `vs`. See also [[histogram]].
(estimate-grid-size vs)(estimate-grid-size vs estimate-method)(estimate-grid-size vs estimate-method opts)Estimates a suitable fastmath.grid size for a 2d histogram (histogram2d) of 2d points vs.
Every method estimates a cell area (in fastmath.stats.bins), converted into the size of the cell type :grid via fastmath.grid/area->size, so the estimated area is consistent across cell types.
Parameters:
vs (sequence of 2d points): each point a [x y] pair (or any 2-element indexable, e.g. Vec2).estimate-method (keyword, default :scott-correlated, nil means the default):
:scott-correlated: the normal-reference rule for cells of one shape and size, taking the correlation of the axes into account (fastmath.stats.bins/scott-correlated); cheap, smaller cells than :scott for correlated data.:scott: the multivariate normal-reference rule (Scott 1992), the area of the best rectangle for uncorrelated normal data (fastmath.stats.bins/scott-2d).:freedman-diaconis: :scott with the standard deviations replaced by IQR / 1.349 (fastmath.stats.bins/freedman-diaconis-2d); robust to outliers and heavy tails, coarse for multimodal data.:cross-validation: the cell size minimizing the leave-one-out cross-validation estimate of the integrated squared error, counted on the grid of histogram2d (fastmath.stats.bins/cross-validation-2d).:shimazaki-shinomoto: the cell size minimizing the cost of Shimazaki and Shinomoto (2007), counted on the grid of histogram2d (fastmath.stats.bins/shimazaki-shinomoto-2d).opts (map, optional):
:grid - the cell type, one of fastmath.grid/cell-names, default: :square:sv - the grid offset (translating vector) of histogram2d, default: [0.0 0.0] (used by the data-driven methods):candidates - the number of candidate cell sizes, default: 200 (data-driven methods):shifts - the number of grid offsets the cost is averaged over, default: 1 (data-driven methods)The rules of thumb (:scott-correlated, :scott, :freedman-diaconis) assume roughly normal data and give coarse cells for multimodal or curved data. The data-driven methods adapt to the shape of the data, pass over the data once per candidate and vary more from sample to sample; for discretized data their cell area is at least four times the product of the smallest gaps between values along the axes.
Points on a line have no 2d density, the size is then the 1d bin width along the line: for any line with :scott-correlated (the 1d Scott width), for a line parallel to an axis with every method (the 1d Freedman-Diaconis width with :freedman-diaconis, the 1d Scott width otherwise).
Returns the estimated size as a double. Falls back to 1.0 when the area cannot be estimated (vs has fewer than 2 points or is constant), rather than propagating 0.0/NaN/Infinity into fastmath.grid/grid. Throws ex-info when :candidates or :shifts is not an integer at least 1.
See also histogram2d, estimate-bins, fastmath.grid/area->size.
Estimates a suitable [[fastmath.grid]] `size` for a 2d histogram ([[histogram2d]]) of 2d points `vs`. Every method estimates a cell area (in `fastmath.stats.bins`), converted into the `size` of the cell type `:grid` via [[fastmath.grid/area->size]], so the estimated area is consistent across cell types. Parameters: - `vs` (sequence of 2d points): each point a `[x y]` pair (or any 2-element indexable, e.g. `Vec2`). - `estimate-method` (keyword, default `:scott-correlated`, `nil` means the default): - `:scott-correlated`: the normal-reference rule for cells of one shape and size, taking the correlation of the axes into account ([[fastmath.stats.bins/scott-correlated]]); cheap, smaller cells than `:scott` for correlated data. - `:scott`: the multivariate normal-reference rule (Scott 1992), the area of the best rectangle for uncorrelated normal data ([[fastmath.stats.bins/scott-2d]]). - `:freedman-diaconis`: `:scott` with the standard deviations replaced by `IQR / 1.349` ([[fastmath.stats.bins/freedman-diaconis-2d]]); robust to outliers and heavy tails, coarse for multimodal data. - `:cross-validation`: the cell size minimizing the leave-one-out cross-validation estimate of the integrated squared error, counted on the grid of [[histogram2d]] ([[fastmath.stats.bins/cross-validation-2d]]). - `:shimazaki-shinomoto`: the cell size minimizing the cost of Shimazaki and Shinomoto (2007), counted on the grid of [[histogram2d]] ([[fastmath.stats.bins/shimazaki-shinomoto-2d]]). - `opts` (map, optional): - `:grid` - the cell type, one of [[fastmath.grid/cell-names]], default: `:square` - `:sv` - the grid offset (translating vector) of [[histogram2d]], default: `[0.0 0.0]` (used by the data-driven methods) - `:candidates` - the number of candidate cell sizes, default: `200` (data-driven methods) - `:shifts` - the number of grid offsets the cost is averaged over, default: `1` (data-driven methods) The rules of thumb (`:scott-correlated`, `:scott`, `:freedman-diaconis`) assume roughly normal data and give coarse cells for multimodal or curved data. The data-driven methods adapt to the shape of the data, pass over the data once per candidate and vary more from sample to sample; for discretized data their cell area is at least four times the product of the smallest gaps between values along the axes. Points on a line have no 2d density, the size is then the 1d bin width along the line: for any line with `:scott-correlated` (the 1d Scott width), for a line parallel to an axis with every method (the 1d Freedman-Diaconis width with `:freedman-diaconis`, the 1d Scott width otherwise). Returns the estimated `size` as a `double`. Falls back to `1.0` when the area cannot be estimated (`vs` has fewer than 2 points or is constant), rather than propagating `0.0`/`NaN`/`Infinity` into [[fastmath.grid/grid]]. Throws `ex-info` when `:candidates` or `:shifts` is not an integer at least 1. See also [[histogram2d]], [[estimate-bins]], [[fastmath.grid/area->size]].
Map of available estimation strategies usable by percentile and quantile.
Each strategy defines how a percentile position is computed from a sorted sample and how the value at a (possibly fractional) position is estimated, following Hyndman and Fan's classification of sample quantile methods. Pass the corresponding keyword as the estimation-strategy argument.
Available strategies:
:legacy - Apache Commons Math's original method, close to :r6 but with min/max returned for out-of-range positions. Default when no strategy is specified.:r1 - Inverse of the empirical CDF, no interpolation (a step function).:r2 - Like :r1, but averages the two candidate values at discontinuities.:r3 - Nearest, rounding to even (SAS default).:r4 - Linear interpolation of the empirical CDF.:r5 - Hazen's method, linear interpolation through the midpoints of the order statistics.:r6 - Weibull's method, linear interpolation of the expectations of the order statistics (used by SPSS and Minitab).:r7 - Linear interpolation of the modes of the order statistics (default in R and NumPy).:r8 - Linear interpolation giving an estimate that is approximately median-unbiased regardless of the underlying distribution.:r9 - Linear interpolation giving an estimate that is approximately unbiased for a normal distribution.See also percentile, quantile.
Map of available estimation strategies usable by [[percentile]] and [[quantile]]. Each strategy defines how a percentile position is computed from a sorted sample and how the value at a (possibly fractional) position is estimated, following Hyndman and Fan's classification of sample quantile methods. Pass the corresponding keyword as the `estimation-strategy` argument. Available strategies: - `:legacy` - Apache Commons Math's original method, close to `:r6` but with min/max returned for out-of-range positions. Default when no strategy is specified. - `:r1` - Inverse of the empirical CDF, no interpolation (a step function). - `:r2` - Like `:r1`, but averages the two candidate values at discontinuities. - `:r3` - Nearest, rounding to even (SAS default). - `:r4` - Linear interpolation of the empirical CDF. - `:r5` - Hazen's method, linear interpolation through the midpoints of the order statistics. - `:r6` - Weibull's method, linear interpolation of the expectations of the order statistics (used by SPSS and Minitab). - `:r7` - Linear interpolation of the modes of the order statistics (default in R and NumPy). - `:r8` - Linear interpolation giving an estimate that is approximately median-unbiased regardless of the underlying distribution. - `:r9` - Linear interpolation giving an estimate that is approximately unbiased for a normal distribution. See also [[percentile]], [[quantile]].
(eta-sq [group1 group2])(eta-sq group1 group2)Calculates a measure of association between two sequences, named eta-sq (Eta-squared).
Note: The current implementation calculates the R-squared coefficient of determination from a simple linear regression where the first input sequence (group1) is treated as the dependent variable and the second (group2) as the independent variable. In this context, it quantifies the proportion of the variance in group1 that is linearly predictable from group2.
Parameters:
group1 (seq of numbers): The first sequence (treated as dependent variable).group2 (seq of numbers): The second sequence (treated as independent variable).Returns the calculated R-squared value as a double [0.0, 1.0].
Interpretation:
group2 explains none of the variance in group1 linearly.group2 linearly explains all the variance in group1.While Eta-squared ($\eta^2$) is commonly used in ANOVA to quantify the proportion of variance in a dependent variable explained by group membership, this function's calculation method differs from the standard ANOVA $\eta^2$ unless group2 explicitly represents numeric codes for two groups.
See also r2-determination (which is equivalent to this function), pearson-correlation, omega-sq, epsilon-sq, one-way-anova-test.
Calculates a measure of association between two sequences, named `eta-sq` (Eta-squared). *Note*: The current implementation calculates the R-squared coefficient of determination from a simple linear regression where the first input sequence (`group1`) is treated as the dependent variable and the second (`group2`) as the independent variable. In this context, it quantifies the proportion of the variance in `group1` that is linearly predictable from `group2`. Parameters: - `group1` (seq of numbers): The first sequence (treated as dependent variable). - `group2` (seq of numbers): The second sequence (treated as independent variable). Returns the calculated R-squared value as a double [0.0, 1.0]. Interpretation: - 0.0 indicates that `group2` explains none of the variance in `group1` linearly. - 1.0 indicates that `group2` linearly explains all the variance in `group1`. While Eta-squared ($\eta^2$) is commonly used in ANOVA to quantify the proportion of variance in a dependent variable explained by group membership, this function's calculation method differs from the standard ANOVA $\eta^2$ unless `group2` explicitly represents numeric codes for two groups. See also [[r2-determination]] (which is equivalent to this function), [[pearson-correlation]], [[omega-sq]], [[epsilon-sq]], [[one-way-anova-test]].
(expectile vs tau)(expectile vs weights tau)Calculate the tau-th expectile of a sequence vs.
Expectiles are related to quantiles but are determined by minimizing an
asymmetrically weighted sum of squared differences, rather than absolute
differences. The tau parameter controls the asymmetry.
A key property is that the expectile for tau = 0.5 is equal to the mean.
The calculation involves finding the value t such that the weighted sum
of w_i * (v_i - t) is zero, where the effective weights depend on tau and whether
v_i is above or below t.
Parameters:
vs: Sequence of data values.weights (optional): Sequence of corresponding non-negative weights.
Must have the same count as vs. If omitted, calculates the unweighted expectile.tau: The expectile level, a value between 0.0 and 1.0 (inclusive).Returns the calculated expectile as a double.
Calculate the tau-th expectile of a sequence `vs`. Expectiles are related to quantiles but are determined by minimizing an asymmetrically weighted sum of squared differences, rather than absolute differences. The `tau` parameter controls the asymmetry. A key property is that the expectile for `tau = 0.5` is equal to the [[mean]]. The calculation involves finding the value `t` such that the weighted sum of `w_i * (v_i - t)` is zero, where the effective weights depend on `tau` and whether `v_i` is above or below `t`. Parameters: - `vs`: Sequence of data values. - `weights` (optional): Sequence of corresponding non-negative weights. Must have the same count as `vs`. If omitted, calculates the unweighted expectile. - `tau`: The expectile level, a value between 0.0 and 1.0 (inclusive). Returns the calculated expectile as a double. See also [[quantile]], [[mean]], [[median]].
(extent vs)(extent vs mean?)Calculates the minimum and maximum values of vs, optionally together with the mean.
Parameters:
vs (sequence of numbers): Input data.mean? (boolean): Whether to append the mean value to the result. Defaults to true.Returns a 2-element vector [min max] when mean? is false, or a 3-element vector [min max mean] when mean? is true.
Calculates the minimum and maximum values of `vs`, optionally together with the mean. Parameters: - `vs` (sequence of numbers): Input data. - `mean?` (boolean): Whether to append the mean value to the result. Defaults to `true`. Returns a 2-element vector `[min max]` when `mean?` is `false`, or a 3-element vector `[min max mean]` when `mean?` is `true`. See also [[span]], [[maximum]], [[minimum]], [[mean]].
(f-test xs ys)(f-test xs ys {:keys [sides alpha] :or {sides :two-sided alpha 0.05}})Performs an F-test to compare the variances of two independent samples.
The test assesses the null hypothesis that the variances of the populations
from which xs and ys are drawn are equal.
Assumes independence of samples. The test is sensitive to departures from the assumption that both populations are normally distributed.
Parameters:
xs (seq of numbers): The first sample.ys (seq of numbers): The second sample.params (map, optional): Options map:
:sides (keyword, default :two-sided): Specifies the alternative hypothesis
regarding the ratio of variances (Var(xs) / Var(ys)).
:two-sided (default): Variances are not equal (ratio != 1).:one-sided-greater: Variance of xs is greater than variance of ys (ratio > 1).:one-sided-less: Variance of xs is less than variance of ys (ratio < 1).:alpha (double, default 0.05): Significance level for the confidence interval.Returns a map containing:
:F: The calculated F-statistic (ratio of sample variances: Var(xs) / Var(ys)).:stat: Alias for :F.:estimate: Alias for :F, representing the estimated ratio of variances.:df: Degrees of freedom as [numerator-df, denominator-df], corresponding to [(count xs)-1, (count ys)-1].:n: Sample sizes as [count xs, count ys].:nx: Sample size of xs.:ny: Sample size of ys.:sides: The alternative hypothesis side used (:two-sided, :one-sided-greater, or :one-sided-less).:test-type: Alias for :sides.:p-value: The p-value associated with the F-statistic and the specified :sides.:confidence-interval: A confidence interval for the true ratio of the population variances (Var(xs) / Var(ys)).Performs an F-test to compare the variances of two independent samples.
The test assesses the null hypothesis that the variances of the populations
from which `xs` and `ys` are drawn are equal.
Assumes independence of samples. The test is sensitive to departures from
the assumption that both populations are normally distributed.
Parameters:
- `xs` (seq of numbers): The first sample.
- `ys` (seq of numbers): The second sample.
- `params` (map, optional): Options map:
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis
regarding the ratio of variances (Var(xs) / Var(ys)).
- `:two-sided` (default): Variances are not equal (ratio != 1).
- `:one-sided-greater`: Variance of `xs` is greater than variance of `ys` (ratio > 1).
- `:one-sided-less`: Variance of `xs` is less than variance of `ys` (ratio < 1).
- `:alpha` (double, default `0.05`): Significance level for the confidence interval.
Returns a map containing:
- `:F`: The calculated F-statistic (ratio of sample variances: Var(xs) / Var(ys)).
- `:stat`: Alias for `:F`.
- `:estimate`: Alias for `:F`, representing the estimated ratio of variances.
- `:df`: Degrees of freedom as `[numerator-df, denominator-df]`, corresponding to `[(count xs)-1, (count ys)-1]`.
- `:n`: Sample sizes as `[count xs, count ys]`.
- `:nx`: Sample size of `xs`.
- `:ny`: Sample size of `ys`.
- `:sides`: The alternative hypothesis side used (`:two-sided`, `:one-sided-greater`, or `:one-sided-less`).
- `:test-type`: Alias for `:sides`.
- `:p-value`: The p-value associated with the F-statistic and the specified `:sides`.
- `:confidence-interval`: A confidence interval for the true ratio of the population variances (Var(xs) / Var(ys)).(fligner-killeen-test xss)(fligner-killeen-test xss {:keys [sides] :or {sides :one-sided-greater}})Performs the Fligner-Killeen test for homogeneity of variances across two or more groups.
The Fligner-Killeen test is a non-parametric test that assesses the null hypothesis that the variances of the groups are equal. It is robust against departures from normality. The test is based on ranks of the absolute deviations from the group medians.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations.params (map, optional): Options map with the following key:
:sides (keyword, default :one-sided-greater): Alternative hypothesis side for the Chi-squared test.
Possible values: :one-sided-greater, :one-sided-less, :two-sided.Returns a map containing:
:chi2: The Fligner-Killeen test statistic (Chi-squared value).:stat: Alias for :chi2.:p-value: The p-value for the test.:df: Degrees of freedom for the test (number of groups - 1).:n: Sequence of sample sizes for each group.:SSt: Sum of squares between groups (treatment) based on transformed ranks.:SSe: Sum of squares within groups (error) based on transformed ranks.:DFt: Degrees of freedom between groups.:DFe: Degrees of freedom within groups.:MSt: Mean square between groups.:MSe: Mean square within groups.:sides: Test side used.Performs the Fligner-Killeen test for homogeneity of variances across two or more groups.
The Fligner-Killeen test is a non-parametric test that assesses the null hypothesis
that the variances of the groups are equal. It is robust against departures from normality.
The test is based on ranks of the absolute deviations from the group medians.
Parameters:
- `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations.
- `params` (map, optional): Options map with the following key:
- `:sides` (keyword, default `:one-sided-greater`): Alternative hypothesis side for the Chi-squared test.
Possible values: `:one-sided-greater`, `:one-sided-less`, `:two-sided`.
Returns a map containing:
- `:chi2`: The Fligner-Killeen test statistic (Chi-squared value).
- `:stat`: Alias for `:chi2`.
- `:p-value`: The p-value for the test.
- `:df`: Degrees of freedom for the test (number of groups - 1).
- `:n`: Sequence of sample sizes for each group.
- `:SSt`: Sum of squares between groups (treatment) based on transformed ranks.
- `:SSe`: Sum of squares within groups (error) based on transformed ranks.
- `:DFt`: Degrees of freedom between groups.
- `:DFe`: Degrees of freedom within groups.
- `:MSt`: Mean square between groups.
- `:MSe`: Mean square within groups.
- `:sides`: Test side used.(freeman-tukey-test contingency-table-or-xs)(freeman-tukey-test contingency-table-or-xs params)Freeman-Tukey test, a power divergence test for lambda -0.5
Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Freeman-Tukey test, a power divergence test for `lambda` -0.5
Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(geomean vs)(geomean vs weights)Calculates the geometric mean of a sequence vs.
The geometric mean is suitable for averaging ratios or rates of change and requires all values in the sequence to be positive. It is calculated as the n-th root of the product of n numbers.
Parameters:
vs: Sequence of numbers. Non-positive values will result in NaN or 0.0 due
to the internal use of log.weights (optional): Sequence of non-negative weights corresponding to vs.
Must have the same count as vs.Returns the calculated geometric mean as a double.
Calculates the geometric mean of a sequence `vs`.
The geometric mean is suitable for averaging ratios or rates of change and requires
all values in the sequence to be positive. It is calculated as the n-th root
of the product of n numbers.
Parameters:
- `vs`: Sequence of numbers. Non-positive values will result in `NaN` or `0.0` due
to the internal use of `log`.
- `weights` (optional): Sequence of non-negative weights corresponding to `vs`.
Must have the same count as `vs`.
Returns the calculated geometric mean as a double.
See also [[mean]], [[harmean]], [[powmean]].(glass-delta [group1 group2])(glass-delta group1 group2)Calculates Glass's delta (Δ), an effect size measure for the difference between two group means, using the standard deviation of the control group.
Glass's delta is used to quantify the magnitude of the difference between an experimental group and a control group, specifically when the control group's standard deviation is considered a better estimate of the population standard deviation than a pooled variance.
Parameters:
group1 (seq of numbers): The experimental group.group2 (seq of numbers): The control group.Returns the calculated Glass's delta as a double.
This measure is less common than cohens-d or hedges-g but is preferred
when the intervention is expected to affect the variance or when group2 (the control)
is clearly the baseline against which variability should be assessed.
Calculates Glass's delta (Δ), an effect size measure for the difference between two group means, using the standard deviation of the control group. Glass's delta is used to quantify the magnitude of the difference between an experimental group and a control group, specifically when the control group's standard deviation is considered a better estimate of the population standard deviation than a pooled variance. Parameters: - `group1` (seq of numbers): The experimental group. - `group2` (seq of numbers): The control group. Returns the calculated Glass's delta as a double. This measure is less common than [[cohens-d]] or [[hedges-g]] but is preferred when the intervention is expected to affect the variance or when group2 (the control) is clearly the baseline against which variability should be assessed. See also [[cohens-d]], [[hedges-g]].
(harmean vs)(harmean vs weights)Calculates the harmonic mean of a sequence vs.
The harmonic mean is the reciprocal of the arithmetic mean of the reciprocals of the observations.
Parameters:
vs: Sequence of numbers. Values must be non-zero.weights (optional): Sequence of non-negative weights corresponding to vs.
Must have the same count as vs.Returns the calculated harmonic mean as a double.
Calculates the harmonic mean of a sequence `vs`. The harmonic mean is the reciprocal of the arithmetic mean of the reciprocals of the observations. Parameters: - `vs`: Sequence of numbers. Values must be non-zero. - `weights` (optional): Sequence of non-negative weights corresponding to `vs`. Must have the same count as `vs`. Returns the calculated harmonic mean as a double. See also [[mean]], [[geomean]], [[powmean]].
(hedges-g [group1 group2])(hedges-g group1 group2)Calculates Hedges's g effect size for comparing the means of two independent groups.
Hedges's g is a standardized measure quantifying the magnitude of the difference between the means of two independent groups. It is similar to Cohen's d but uses the unbiased pooled standard deviation in the denominator.
This implementation calculates g using the unbiased pooled standard deviation as the denominator.
Parameters:
group1, group2 (sequences): The two independent samples directly as arguments.Returns the calculated Hedges's g effect size as a double.
Note: This specific function uses the unbiased pooled standard deviation but does
not apply the small-sample bias correction factor (often denoted as J)
sometimes associated with Hedges's g. For a bias-corrected version, see hedges-g-corrected.
This function is equivalent to calling (cohens-d group1 group2 :unbiased).
See also cohens-d, hedges-g-corrected, glass-delta, pooled-stddev.
Calculates Hedges's g effect size for comparing the means of two independent groups. Hedges's g is a standardized measure quantifying the magnitude of the difference between the means of two independent groups. It is similar to Cohen's d but uses the *unbiased* pooled standard deviation in the denominator. This implementation calculates g using the unbiased pooled standard deviation as the denominator. Parameters: - `group1`, `group2` (sequences): The two independent samples directly as arguments. Returns the calculated Hedges's g effect size as a double. Note: This specific function uses the unbiased pooled standard deviation but does *not* apply the small-sample bias correction factor (often denoted as J) sometimes associated with Hedges's g. For a bias-corrected version, see [[hedges-g-corrected]]. This function is equivalent to calling `(cohens-d group1 group2 :unbiased)`. See also [[cohens-d]], [[hedges-g-corrected]], [[glass-delta]], [[pooled-stddev]].
(hedges-g* [group1 group2])(hedges-g* group1 group2)Calculates a less biased estimate of Hedges's g effect size for comparing the means of two independent groups, using the exact J bias correction.
Hedges's g is a standardized measure of the difference between two means. For small sample sizes, the standard Hedges's g (and Cohen's d) can overestimate the true population effect size. This function applies a specific correction factor, often denoted as J, to mitigate this bias.
The calculation involves:
hedges-g, which uses the unbiased pooled standard deviation).n1 + n2 - 2) using the gamma function.The J factor is calculated as (Gamma(df/2) / (sqrt(df/2) * Gamma((df-1)/2))).
Parameters:
group1 (seq of numbers): The first independent sample.group2 (seq of numbers): The second independent sample.Returns the calculated bias-corrected Hedges's g effect size as a double.
This version of Hedges's g is generally preferred over the standard version or Cohen's d when working with small sample sizes, as it provides a more accurate estimate of the population effect size.
Assumptions:
See also cohens-d, hedges-g (uncorrected), hedges-g-corrected (another correction method).
Calculates a less biased estimate of Hedges's g effect size for comparing the means of two independent groups, using the exact J bias correction. Hedges's g is a standardized measure of the difference between two means. For small sample sizes, the standard Hedges's g (and Cohen's d) can overestimate the true population effect size. This function applies a specific correction factor, often denoted as J, to mitigate this bias. The calculation involves: 1. Calculating the standard Hedges's g (equivalent to [[hedges-g]], which uses the unbiased pooled standard deviation). 2. Calculating the J correction factor based on the degrees of freedom (`n1 + n2 - 2`) using the gamma function. 3. Multiplying the standard Hedges's g by the J factor. The J factor is calculated as `(Gamma(df/2) / (sqrt(df/2) * Gamma((df-1)/2)))`. Parameters: - `group1` (seq of numbers): The first independent sample. - `group2` (seq of numbers): The second independent sample. Returns the calculated bias-corrected Hedges's g effect size as a double. This version of Hedges's g is generally preferred over the standard version or Cohen's d when working with small sample sizes, as it provides a more accurate estimate of the population effect size. Assumptions: - The two samples are independent. - Data within each group are approximately normally distributed. - Equal variances are assumed for calculating the pooled standard deviation. See also [[cohens-d]], [[hedges-g]] (uncorrected), [[hedges-g-corrected]] (another correction method).
(hedges-g-corrected [group1 group2])(hedges-g-corrected group1 group2)Calculates a small-sample bias-corrected effect size for comparing the means of two independent groups, often referred to as a form of Hedges's g.
This function calculates Cohen's d (cohens-d) using the unbiased
pooled standard deviation (equivalent to hedges-g), and then applies
a specific correction factor designed to reduce the bias in the effect size
estimate for small sample sizes.
The correction factor applied is (1 - 3 / (4 * df - 1)), where df is the
degrees of freedom for the unbiased pooled variance calculation (n1 + n2 - 2).
This corresponds to calling cohens-d-corrected with the :unbiased method
for pooled standard deviation.
Parameters:
group1 (seq of numbers): The first independent sample.group2 (seq of numbers): The second independent sample.Returns the calculated bias-corrected effect size as a double.
Note: This function applies a correction factor. For the more
standard Hedges's g bias correction using the exact gamma function
based correction factor, see hedges-g*.
See also cohens-d, cohens-d-corrected, hedges-g, hedges-g*,
pooled-stddev.
Calculates a small-sample bias-corrected effect size for comparing the means of two independent groups, often referred to as a form of Hedges's g. This function calculates Cohen's d ([[cohens-d]]) using the *unbiased* pooled standard deviation (equivalent to [[hedges-g]]), and then applies a specific correction factor designed to reduce the bias in the effect size estimate for small sample sizes. The correction factor applied is `(1 - 3 / (4 * df - 1))`, where `df` is the degrees of freedom for the unbiased pooled variance calculation (`n1 + n2 - 2`). This corresponds to calling [[cohens-d-corrected]] with the `:unbiased` method for pooled standard deviation. Parameters: - `group1` (seq of numbers): The first independent sample. - `group2` (seq of numbers): The second independent sample. Returns the calculated bias-corrected effect size as a double. Note: This function applies *a* correction factor. For the more standard Hedges's g bias correction using the exact gamma function based correction factor, see [[hedges-g*]]. See also [[cohens-d]], [[cohens-d-corrected]], [[hedges-g]], [[hedges-g*]], [[pooled-stddev]].
(histogram vs)(histogram vs bins-or-estimate-method)(histogram vs bins-or-estimate-method [mn mx])(histogram vs bins-or-estimate-method mn mx)Builds a histogram of vs, partitioning the data into equal-width bins and counting the samples in each.
vs can also be a sequence of sequences, in which case a shared set of bin boundaries is derived across all of them (from their combined extent and the largest estimated bin count), and a histogram is computed for each inner sequence using those boundaries, letting the results be compared directly.
Parameters:
vs (sequence of numbers, or sequence of sequences of numbers): Input data.bins-or-estimate-method (keyword, long or sequence): Number of bins, or bin-count estimation method, see estimate-bins (default :freedman-diaconis). Alternatively, a sequence of numbers to use directly as explicit bin boundaries (intervals).mn, mx (doubles, or a 2-element vector [mn mx]): Optional bounds. When provided, data is filtered to keep only values in [mn,mx] before binning, and this range is used instead of the data extent. Ignored when bins-or-estimate-method is a sequence of boundaries, since its own extent is used instead.Returns a map (or, when vs is a sequence of sequences, a sequence of such maps, one per inner sequence, sharing the same :intervals) with the following keys:
:size: number of bins.:step: average distance between bins.:samples: number of samples actually used (after filtering to [mn,mx]).:min, :max: lower and upper bounds used for binning.:bins: sequence of pairs [bin-lower-bound bin-count].:bins-maps: sequence of maps, one per bin, with keys :min (lower bound), :max (upper bound), :mid (middle value), :step (actual bin width), :count (number of elements), :avg (average value of the elements in the bin), and :probability (fraction of samples in the bin).:intervals: the bin boundaries used to build the histogram.:frequencies: a map from each bin's :avg to its :count.If the difference between mn and mx is 0, the number of bins is set to 1.
See also estimate-bins.
Builds a histogram of `vs`, partitioning the data into equal-width bins and counting the samples in each. `vs` can also be a sequence of sequences, in which case a shared set of bin boundaries is derived across all of them (from their combined extent and the largest estimated bin count), and a histogram is computed for each inner sequence using those boundaries, letting the results be compared directly. Parameters: - `vs` (sequence of numbers, or sequence of sequences of numbers): Input data. - `bins-or-estimate-method` (keyword, long or sequence): Number of bins, or bin-count estimation method, see [[estimate-bins]] (default `:freedman-diaconis`). Alternatively, a sequence of numbers to use directly as explicit bin boundaries (intervals). - `mn`, `mx` (doubles, or a 2-element vector `[mn mx]`): Optional bounds. When provided, data is filtered to keep only values in `[mn,mx]` before binning, and this range is used instead of the data extent. Ignored when `bins-or-estimate-method` is a sequence of boundaries, since its own extent is used instead. Returns a map (or, when `vs` is a sequence of sequences, a sequence of such maps, one per inner sequence, sharing the same `:intervals`) with the following keys: - `:size`: number of bins. - `:step`: average distance between bins. - `:samples`: number of samples actually used (after filtering to `[mn,mx]`). - `:min`, `:max`: lower and upper bounds used for binning. - `:bins`: sequence of pairs `[bin-lower-bound bin-count]`. - `:bins-maps`: sequence of maps, one per bin, with keys `:min` (lower bound), `:max` (upper bound), `:mid` (middle value), `:step` (actual bin width), `:count` (number of elements), `:avg` (average value of the elements in the bin), and `:probability` (fraction of samples in the bin). - `:intervals`: the bin boundaries used to build the histogram. - `:frequencies`: a map from each bin's `:avg` to its `:count`. If the difference between `mn` and `mx` is `0`, the number of bins is set to `1`. See also [[estimate-bins]].
(histogram2d vs)(histogram2d vs size-or-estimate-method)(histogram2d vs size-or-estimate-method opts)Builds a 2d histogram of 2d points vs, binning them onto a fastmath.grid tessellation.
Unlike histogram, only occupied cells are returned (sparse) — a non-square, non-rectangular tessellation of a bounding box can otherwise include far more empty edge cells than a square binning would. Only a single sequence of points is supported (no histogram-style sequence-of-sequences overload).
Parameters:
vs (sequence of 2d points): each point a [x y] pair (or any 2-element indexable, e.g. Vec2).size-or-estimate-method (double or keyword, default :scott-correlated, nil means the default): explicit fastmath.grid/grid size (bin width, i.e. anchor-to-anchor spacing), or a bin-size estimation method keyword, see estimate-grid-size.opts (map, optional):
:grid - the cell type (keyword), one of fastmath.grid/cell-names, default: :square:sv - the grid translating vector [sx sy], see fastmath.grid/grid, default: [0.0 0.0]:candidates, :shifts - options of the data-driven estimation methods, see estimate-grid-sizeThe size is estimated on the same grid (cell type and offset) the histogram is built on.
Returns a map, adapted key-by-key from histogram's 1d result (some 1d keys have no 2d equivalent and are replaced or dropped — see each key below):
:size: number of occupied bins (not all cells in the bounding region).:step: the grid's resolved size.:samples: number of input points ((count vs)).:min, :max: the 2d bounding box of vs, as [x y] pairs. nil when vs is empty.:bins: sequence of [cell-coords count] pairs (cell-coords is a [q r] Vec2, from fastmath.grid/coords->cell) — the 2d analogue of 1d [bin-lower-bound count].:bins-maps: sequence of maps, one per occupied cell, with keys :cell ([q r]), :mid (the cell's geometric center, fastmath.grid/cell->mid), :avg (centroid of the actual points landing in that cell — distinct from :mid), :count, :probability (fraction of samples in the bin). No :min/:max/:step (no per-bin interval bounds in 2d) and no :corners (derivable from :grid + :cell via fastmath.grid/corners).:grid: the constructed grid object (satisfies fastmath.protocols/GridProto; not the cell type keyword of the :grid option) — lets callers call fastmath.grid/corners/fastmath.grid/cell->anchor/etc. on any returned cell without reconstructing the grid. Replaces 1d :intervals, which has no 2d equivalent.:frequencies: a map from each occupied cell's coords to its count (repurposed from 1d's avg-value-keyed map, which would have duplicated :bins in 2d).Empty vs returns a well-formed, empty result (:size 0, :samples 0, :min/:max nil, :bins/:bins-maps (), :frequencies {}) rather than throwing.
See also histogram, estimate-grid-size, fastmath.grid/grid.
Builds a 2d histogram of 2d points `vs`, binning them onto a [[fastmath.grid]] tessellation.
Unlike [[histogram]], only occupied cells are returned (sparse) — a non-square, non-rectangular tessellation of a bounding box can otherwise include far more empty edge cells than a square binning would. Only a single sequence of points is supported (no [[histogram]]-style sequence-of-sequences overload).
Parameters:
- `vs` (sequence of 2d points): each point a `[x y]` pair (or any 2-element indexable, e.g. `Vec2`).
- `size-or-estimate-method` (double or keyword, default `:scott-correlated`, `nil` means the default): explicit [[fastmath.grid/grid]] `size` (bin width, i.e. anchor-to-anchor spacing), or a bin-size estimation method keyword, see [[estimate-grid-size]].
- `opts` (map, optional):
- `:grid` - the cell type (keyword), one of [[fastmath.grid/cell-names]], default: `:square`
- `:sv` - the grid translating vector `[sx sy]`, see [[fastmath.grid/grid]], default: `[0.0 0.0]`
- `:candidates`, `:shifts` - options of the data-driven estimation methods, see [[estimate-grid-size]]
The size is estimated on the same grid (cell type and offset) the histogram is built on.
Returns a map, adapted key-by-key from [[histogram]]'s 1d result (some 1d keys have no 2d equivalent and are replaced or dropped — see each key below):
- `:size`: number of *occupied* bins (not all cells in the bounding region).
- `:step`: the grid's resolved `size`.
- `:samples`: number of input points (`(count vs)`).
- `:min`, `:max`: the 2d bounding box of `vs`, as `[x y]` pairs. `nil` when `vs` is empty.
- `:bins`: sequence of `[cell-coords count]` pairs (cell-coords is a `[q r]` `Vec2`, from [[fastmath.grid/coords->cell]]) — the 2d analogue of 1d `[bin-lower-bound count]`.
- `:bins-maps`: sequence of maps, one per occupied cell, with keys `:cell` (`[q r]`), `:mid` (the cell's geometric center, [[fastmath.grid/cell->mid]]), `:avg` (centroid of the *actual points* landing in that cell — distinct from `:mid`), `:count`, `:probability` (fraction of samples in the bin). No `:min`/`:max`/`:step` (no per-bin interval bounds in 2d) and no `:corners` (derivable from `:grid` + `:cell` via [[fastmath.grid/corners]]).
- `:grid`: the constructed grid object (satisfies [[fastmath.protocols/GridProto]]; not the cell type keyword of the `:grid` option) — lets callers call [[fastmath.grid/corners]]/[[fastmath.grid/cell->anchor]]/etc. on any returned cell without reconstructing the grid. Replaces 1d `:intervals`, which has no 2d equivalent.
- `:frequencies`: a map from each occupied cell's coords to its count (repurposed from 1d's avg-value-keyed map, which would have duplicated `:bins` in 2d).
Empty `vs` returns a well-formed, empty result (`:size` `0`, `:samples` `0`, `:min`/`:max` `nil`, `:bins`/`:bins-maps` `()`, `:frequencies` `{}`) rather than throwing.
See also [[histogram]], [[estimate-grid-size]], [[fastmath.grid/grid]].(hpdi-extent vs)(hpdi-extent vs size)Calculates the Highest Posterior Density Interval (HPDI) of vs together with its median.
Unlike the symmetric pi-extent, which fixes the probability mass on each tail, the HPDI is the narrowest interval that contains the target probability content size of the (sorted) samples. It is found by sliding a fixed-size window across the sorted data and picking the position with the smallest width.
Parameters:
vs (sequence of numbers): Input data.size (double): Target probability content of the interval, in range (0,1). Defaults to 0.95.Returns a 3-element vector [lower-bound upper-bound median].
See also pi-extent, quantile-extent.
Calculates the Highest Posterior Density Interval (HPDI) of `vs` together with its median. Unlike the symmetric [[pi-extent]], which fixes the probability mass on each tail, the HPDI is the narrowest interval that contains the target probability content `size` of the (sorted) samples. It is found by sliding a fixed-size window across the sorted data and picking the position with the smallest width. Parameters: - `vs` (sequence of numbers): Input data. - `size` (double): Target probability content of the interval, in range `(0,1)`. Defaults to `0.95`. Returns a 3-element vector `[lower-bound upper-bound median]`. See also [[pi-extent]], [[quantile-extent]].
(inner-fence-extent vs)(inner-fence-extent vs estimation-strategy)Calculates the lower and upper inner fence thresholds (LIF and UIF) of vs, together with its median.
The inner fences are the classic Tukey box-and-whisker plot outlier thresholds, computed from Q1 and Q3, the 25th and 75th percentiles, and IQR = Q3 - Q1:
Q1 - 1.5*IQR.Q3 + 1.5*IQR.Unlike adjacent-values, these are threshold values and not necessarily values present in vs. Values below LIF or above UIF are considered (mild) outliers, see outliers and remove-outliers.
Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a 3-element vector [LIF UIF median].
See also outer-fence-extent, adjacent-values, iqr, percentile-extent.
Calculates the lower and upper inner fence thresholds (LIF and UIF) of `vs`, together with its median. The inner fences are the classic Tukey box-and-whisker plot outlier thresholds, computed from `Q1` and `Q3`, the 25th and 75th percentiles, and `IQR = Q3 - Q1`: - LIF is the lower inner fence, `Q1 - 1.5*IQR`. - UIF is the upper inner fence, `Q3 + 1.5*IQR`. Unlike [[adjacent-values]], these are threshold values and not necessarily values present in `vs`. Values below LIF or above UIF are considered (mild) outliers, see [[outliers]] and [[remove-outliers]]. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a 3-element vector `[LIF UIF median]`. See also [[outer-fence-extent]], [[adjacent-values]], [[iqr]], [[percentile-extent]].
(iqr vs)(iqr vs estimation-strategy)Calculates the interquartile range (IQR) of vs.
The IQR is the difference between the third quartile (75th percentile) and the first quartile (25th percentile), and is a robust measure of statistical dispersion that is insensitive to outliers.
Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns the IQR as a double.
See also percentile-extent, inner-fence-extent, outer-fence-extent.
Calculates the interquartile range (IQR) of `vs`. The IQR is the difference between the third quartile (75th percentile) and the first quartile (25th percentile), and is a robust measure of statistical dispersion that is insensitive to outliers. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns the IQR as a double. See also [[percentile-extent]], [[inner-fence-extent]], [[outer-fence-extent]].
(jarque-bera-test xs)(jarque-bera-test xs params)(jarque-bera-test xs skew kurt {:keys [sides] :or {sides :one-sided-greater}})Performs the Jarque-Bera goodness-of-fit test to determine if sample data exhibits skewness and kurtosis consistent with a normal distribution.
The test assesses the null hypothesis that the data comes from a normally distributed population (i.e., population skewness is 0 and population excess kurtosis is 0).
The test statistic is calculated as:
JB = (n/6) * (S^2 + (1/4)*K^2)
where n is the sample size, S is the sample skewness (using :g1 type),
and K is the excess kurtosis :g2.
Under the null hypothesis, the JB statistic asymptotically follows a Chi-squared
distribution with 2 degrees of freedom.
Parameters:
xs (seq of numbers): The sample data.skew (double, optional): A pre-calculated sample skewness value (type :g1).
If omitted, it's calculated from xs.kurt (double, optional): A pre-calculated sample excess kurtosis value (type :g2).
If omitted, it's calculated from xs.params (map, optional): Options map:
:sides (keyword, default :one-sided-greater): Specifies the side(s) of the
Chi-squared(2) distribution used for p-value calculation.
:one-sided-greater (default and standard for JB): Tests if the JB statistic is
significantly large, indicating departure from normality.:one-sided-less: Tests if the statistic is significantly small.:two-sided: Tests if the statistic is extreme in either tail.Returns a map containing:
:Z: The calculated Jarque-Bera test statistic (labeled :Z for consistency,
though it follows Chi-squared(2)).:stat: Alias for :Z.:p-value: The p-value associated with the test statistic and :sides, derived
from the Chi-squared(2) distribution.:skewness: The sample skewness (type :g1) used in the calculation.:kurtosis: The sample kurtosis (type :g2) used in the calculation.See also skewness-test, kurtosis-test, normality-test, bonett-seier-test.
Performs the Jarque-Bera goodness-of-fit test to determine if sample data
exhibits skewness and kurtosis consistent with a normal distribution.
The test assesses the null hypothesis that the data comes from a normally
distributed population (i.e., population skewness is 0 and population excess
kurtosis is 0).
The test statistic is calculated as:
`JB = (n/6) * (S^2 + (1/4)*K^2)`
where `n` is the sample size, `S` is the sample skewness (using `:g1` type),
and `K` is the excess kurtosis `:g2`.
Under the null hypothesis, the JB statistic asymptotically follows a Chi-squared
distribution with 2 degrees of freedom.
Parameters:
- `xs` (seq of numbers): The sample data.
- `skew` (double, optional): A pre-calculated sample skewness value (type `:g1`).
If omitted, it's calculated from `xs`.
- `kurt` (double, optional): A pre-calculated sample *excess* kurtosis value (type `:g2`).
If omitted, it's calculated from `xs`.
- `params` (map, optional): Options map:
- `:sides` (keyword, default `:one-sided-greater`): Specifies the side(s) of the
Chi-squared(2) distribution used for p-value calculation.
- `:one-sided-greater` (default and standard for JB): Tests if the JB statistic is
significantly large, indicating departure from normality.
- `:one-sided-less`: Tests if the statistic is significantly small.
- `:two-sided`: Tests if the statistic is extreme in either tail.
Returns a map containing:
- `:Z`: The calculated Jarque-Bera test statistic (labeled `:Z` for consistency,
though it follows Chi-squared(2)).
- `:stat`: Alias for `:Z`.
- `:p-value`: The p-value associated with the test statistic and `:sides`, derived
from the Chi-squared(2) distribution.
- `:skewness`: The sample skewness (type `:g1`) used in the calculation.
- `:kurtosis`: The sample kurtosis (type `:g2`) used in the calculation.
See also [[skewness-test]], [[kurtosis-test]], [[normality-test]], [[bonett-seier-test]].(jensen-shannon-divergence [vs1 vs2])(jensen-shannon-divergence vs1 vs2)Jensen-Shannon divergence of two sequences.
Jensen-Shannon divergence of two sequences.
(joint-entropy group1 group2)(joint-entropy group1 group2 log-base)Calculates the joint Shannon entropy H(X,Y) of the empirical joint distribution of two sequences.
The joint entropy quantifies the total uncertainty contained in the pair of variables (group1, group2) considered together.
Parameters:
group1, group2 (sequences): Two sequences of (typically categorical) observations of the same length, paired by index.log-base (double, optional): The logarithm base used, see entropy. Defaults to e.Returns the calculated joint Shannon entropy as a double, always >= 0.0. Always >= max(H(group1), H(group2)) and <= H(group1) + H(group2).
See also entropy, mutual-information, theils-u, contingency-table.
Calculates the joint Shannon entropy H(X,Y) of the empirical joint distribution of two sequences. The joint entropy quantifies the total uncertainty contained in the pair of variables `(group1, group2)` considered together. Parameters: - `group1`, `group2` (sequences): Two sequences of (typically categorical) observations of the same length, paired by index. - `log-base` (double, optional): The logarithm base used, see [[entropy]]. Defaults to `e`. Returns the calculated joint Shannon entropy as a double, always `>= 0.0`. Always `>= max(H(group1), H(group2))` and `<= H(group1) + H(group2)`. See also [[entropy]], [[mutual-information]], [[theils-u]], [[contingency-table]].
(kendall-correlation [vs1 vs2])(kendall-correlation vs1 vs2)Calculates Kendall's rank correlation coefficient (Kendall's Tau) between two sequences.
Kendall's Tau is a non-parametric statistic used to measure the ordinal association between two measured quantities. It assesses the degree of similarity between the orderings of data when ranked by each of the quantities.
The coefficient value ranges from -1.0 (perfect disagreement in ranking) to 1.0 (perfect agreement in ranking), with 0.0 indicating no monotonic relationship. Unlike Pearson correlation, it does not require the relationship to be linear.
Parameters:
[vs1 vs2] (sequence of two sequences): A sequence containing the two sequences of numbers.vs1, vs2 (sequences): The two sequences of numbers directly as arguments.Both input sequences must contain only numbers and must have the same length.
Returns the calculated Kendall's Tau coefficient as a double.
See also pearson-correlation, spearman-correlation, correlation.
Calculates Kendall's rank correlation coefficient (Kendall's Tau) between two sequences. Kendall's Tau is a non-parametric statistic used to measure the ordinal association between two measured quantities. It assesses the degree of similarity between the orderings of data when ranked by each of the quantities. The coefficient value ranges from -1.0 (perfect disagreement in ranking) to 1.0 (perfect agreement in ranking), with 0.0 indicating no monotonic relationship. Unlike Pearson correlation, it does not require the relationship to be linear. Parameters: - `[vs1 vs2]` (sequence of two sequences): A sequence containing the two sequences of numbers. - `vs1`, `vs2` (sequences): The two sequences of numbers directly as arguments. Both input sequences must contain only numbers and must have the same length. Returns the calculated Kendall's Tau coefficient as a double. See also [[pearson-correlation]], [[spearman-correlation]], [[correlation]].
(kruskal-test xss)(kruskal-test xss {:keys [sides] :or {sides :right}})Performs the Kruskal-Wallis H-test (rank sum test) for independent samples.
The Kruskal-Wallis test is a non-parametric alternative to one-way ANOVA. It determines whether there is a statistically significant difference between the distributions of two or more independent groups. It does not assume normality but requires that distributions have a similar shape for the test to be valid.
Parameters:
data-groups (vector of sequences): A collection where each element is a sequence
representing a group of observations.:sides key with values of: :right (default), :left or :bothReturns a map containing:
:stat: The Kruskal-Wallis H statistic.:n: Total number of observations across all groups.:df: Degrees of freedom (number of groups - 1).:k: Number of groups.:sides: Test side:p-value: The p-value for the test (null hypothesis: all groups have the same distribution).Performs the Kruskal-Wallis H-test (rank sum test) for independent samples. The Kruskal-Wallis test is a non-parametric alternative to one-way ANOVA. It determines whether there is a statistically significant difference between the distributions of two or more independent groups. It does not assume normality but requires that distributions have a similar shape for the test to be valid. Parameters: - `data-groups` (vector of sequences): A collection where each element is a sequence representing a group of observations. - a map containing `:sides` key with values of: `:right` (default), `:left` or `:both` Returns a map containing: - `:stat`: The Kruskal-Wallis H statistic. - `:n`: Total number of observations across all groups. - `:df`: Degrees of freedom (number of groups - 1). - `:k`: Number of groups. - `:sides`: Test side - `:p-value`: The p-value for the test (null hypothesis: all groups have the same distribution).
(ks-statistic xs distribution)(ks-statistic xs distribution {:keys [sorted?]})Calculates the Kolmogorov-Smirnov statistic of a sample against a distribution.
The statistic is the largest absolute difference between the empirical cumulative distribution function of xs and the cumulative distribution function of distribution. Unlike ks-test-one-sample it returns the statistic only, keeps all observations (ties included) and does not compute a p-value, so it is suitable as an objective for fitting a distribution or for ranking candidate distributions.
Parameters:
xs (sequence of numbers): The sample.distribution: A fastmath.random distribution.opts (map, optional):
:sorted? (boolean, default false): Set to true when xs is already sorted ascending, to skip sorting.Returns the statistic as a double, in [0, 1]. Throws ex-info for empty xs. The result is NaN when the cumulative distribution function returns NaN.
For discrete and mixed distributions the statistic is still computed from the cumulative distribution function, but it is only descriptive: its null distribution is not the one used by ks-test-one-sample.
See also ks-test-one-sample, cvm-statistic, ad-statistic.
Calculates the Kolmogorov-Smirnov statistic of a sample against a distribution. The statistic is the largest absolute difference between the empirical cumulative distribution function of `xs` and the cumulative distribution function of `distribution`. Unlike [[ks-test-one-sample]] it returns the statistic only, keeps all observations (ties included) and does not compute a p-value, so it is suitable as an objective for fitting a distribution or for ranking candidate distributions. Parameters: - `xs` (sequence of numbers): The sample. - `distribution`: A `fastmath.random` distribution. - `opts` (map, optional): - `:sorted?` (boolean, default `false`): Set to `true` when `xs` is already sorted ascending, to skip sorting. Returns the statistic as a double, in `[0, 1]`. Throws `ex-info` for empty `xs`. The result is `NaN` when the cumulative distribution function returns `NaN`. For discrete and mixed distributions the statistic is still computed from the cumulative distribution function, but it is only descriptive: its null distribution is not the one used by [[ks-test-one-sample]]. See also [[ks-test-one-sample]], [[cvm-statistic]], [[ad-statistic]].
(ks-test-one-sample xs)(ks-test-one-sample xs distribution-or-ys)(ks-test-one-sample xs
distribution-or-ys
{:keys [sides kernel bandwidth distinct?]
:or {sides :two-sided kernel :gaussian distinct? true}})Performs the one-sample Kolmogorov-Smirnov (KS) test.
This test compares the empirical cumulative distribution function (ECDF) of a
sample xs against a specified theoretical distribution or the ECDF of
another empirical sample. It assesses the null hypothesis that xs is drawn
from the reference distribution.
Parameters:
xs (seq of numbers): The sample data to be tested.distribution-or-ys (optional):
fastmath.random distribution object to test against. If omitted, defaults
to the standard normal distribution (fastmath.random/default-normal).ys). In this case, an empirical distribution is
estimated from ys using Kernel Density Estimation (KDE) or an enumerated
distribution (see :kernel option).opts (map, optional): Options map:
:sides (keyword, default :two-sided): Specifies the alternative hypothesis
regarding the difference between the ECDF of xs and the reference CDF.
:two-sided (default): Tests if the ECDF of xs is different from the reference CDF.:right: Tests if the ECDF of xs is significantly below the reference CDF (i.e., xs tends to have larger values, stochastically greater).:left: Tests if the ECDF of xs is significantly above the reference CDF (i.e., xs tends to have smaller values, stochastically smaller).:kernel (keyword, default :gaussian): Used only when distribution-or-ys
is a sequence. Specifies the method to estimate the empirical distribution:
:gaussian (or other KDE kernels): Uses Kernel Density Estimation.:enumerated: Creates a discrete empirical distribution from ys.:bandwidth (double, optional): Bandwidth for KDE (if applicable).:distinct? (boolean or keyword, default true): How to handle duplicate values in xs.
true (default): Removes duplicate values from xs before computation.false: Uses all values in xs, including duplicates.:jitter: Adds a small amount of random noise to each value in xs to break ties.Returns a map containing:
:n: Sample size of xs (after applying :distinct?).:dp: Maximum positive difference (ECDF(xs) - CDF(ref)).:dn: Maximum positive difference (CDF(ref) - ECDF(xs)).:d: The KS test statistic (max absolute difference: max(dp, dn)).:stat: The specific statistic used for p-value calculation, depending on :sides (d, dp, or dn).:p-value: The p-value associated with the test statistic and the specified :sides.:sides: The alternative hypothesis side used.Performs the one-sample Kolmogorov-Smirnov (KS) test.
This test compares the empirical cumulative distribution function (ECDF) of a
sample `xs` against a specified theoretical distribution or the ECDF of
another empirical sample. It assesses the null hypothesis that `xs` is drawn
from the reference distribution.
Parameters:
- `xs` (seq of numbers): The sample data to be tested.
- `distribution-or-ys` (optional):
- A `fastmath.random` distribution object to test against. If omitted, defaults
to the standard normal distribution (`fastmath.random/default-normal`).
- A sequence of numbers (`ys`). In this case, an empirical distribution is
estimated from `ys` using Kernel Density Estimation (KDE) or an enumerated
distribution (see `:kernel` option).
- `opts` (map, optional): Options map:
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis
regarding the difference between the ECDF of `xs` and the reference CDF.
- `:two-sided` (default): Tests if the ECDF of `xs` is different from the reference CDF.
- `:right`: Tests if the ECDF of `xs` is significantly *below* the reference CDF (i.e., `xs` tends to have larger values, stochastically greater).
- `:left`: Tests if the ECDF of `xs` is significantly *above* the reference CDF (i.e., `xs` tends to have smaller values, stochastically smaller).
- `:kernel` (keyword, default `:gaussian`): Used only when `distribution-or-ys`
is a sequence. Specifies the method to estimate the empirical distribution:
- `:gaussian` (or other KDE kernels): Uses Kernel Density Estimation.
- `:enumerated`: Creates a discrete empirical distribution from `ys`.
- `:bandwidth` (double, optional): Bandwidth for KDE (if applicable).
- `:distinct?` (boolean or keyword, default `true`): How to handle duplicate values in `xs`.
- `true` (default): Removes duplicate values from `xs` before computation.
- `false`: Uses all values in `xs`, including duplicates.
- `:jitter`: Adds a small amount of random noise to each value in `xs` to break ties.
Returns a map containing:
- `:n`: Sample size of `xs` (after applying `:distinct?`).
- `:dp`: Maximum positive difference (ECDF(xs) - CDF(ref)).
- `:dn`: Maximum positive difference (CDF(ref) - ECDF(xs)).
- `:d`: The KS test statistic (max absolute difference: `max(dp, dn)`).
- `:stat`: The specific statistic used for p-value calculation, depending on `:sides` (`d`, `dp`, or `dn`).
- `:p-value`: The p-value associated with the test statistic and the specified `:sides`.
- `:sides`: The alternative hypothesis side used.(ks-test-two-samples xs ys)(ks-test-two-samples xs
ys
{:keys [method sides distinct? correct?]
:or {sides :two-sided distinct? :ties correct? true}})Performs the two-sample Kolmogorov-Smirnov (KS) test.
This test compares the empirical cumulative distribution functions (ECDFs) of two
independent samples, xs and ys, to assess the null hypothesis that they
are drawn from the same continuous distribution.
Parameters:
xs (seq of numbers): The first sample.ys (seq of numbers): The second sample.opts (map, optional): Options map:
:method (keyword, optional): Specifies the calculation method for the p-value.
:exact: Attempts an exact calculation (suitable for small samples, sensitive to ties). Default if nx * ny < 10000.:approximate: Uses the asymptotic Kolmogorov distribution (suitable for larger samples). Default otherwise.:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): Tests if the distributions differ (ECDFs are different).:right: Tests if xs is stochastically greater than ys (ECDF(xs) is below ECDF(ys)).:left: Tests if xs is stochastically smaller than ys (ECDF(xs) is above ECDF(ys)).:distinct? (keyword or boolean, default :ties): How to handle duplicate values (ties).
:ties (default): Includes all points. Passes information about ties to the :exact calculation method. Accuracy depends on the exact method's tie handling.:jitter: Adds a small amount of random noise to break ties before comparison. A practical approach if exact tie handling is complex or not required.true: Applies distinct to xs and ys separately before combining. May not resolve all ties between the combined samples.false: Uses the data as-is, without attempting to handle ties explicitly (may lead to less accurate p-values, especially with the exact method).:correct? (boolean, default true): Apply continuity correction when using the :exact calculation method for a more accurate p-value especially for smaller sample sizes.Returns a map containing:
:nx: Number of observations in xs (after :distinct? processing if applicable).:ny: Number of observations in ys (after :distinct? processing if applicable).:n: Effective sample size used for asymptotic calculation (nx*ny / (nx+ny)).:dp: Maximum positive difference (ECDF(xs) - ECDF(ys)).:dn: Maximum positive difference (ECDF(ys) - ECDF(xs)).:d: The KS test statistic (max absolute difference: max(dp, dn)).:stat: The specific statistic used for p-value calculation (d, dp, or dn for exact; scaled version for approximate).:KS: Alias for :stat.:p-value: The p-value associated with the test statistic and :sides.:sides: The alternative hypothesis side used.:method: The calculation method used (:exact or :approximate).Note on Ties: The KS test is strictly defined for continuous distributions where ties have zero probability.
The presence of ties in sample data affects the p-value calculation. The :distinct? option provides ways to manage this, with :jitter being a common pragmatic choice.
Performs the two-sample Kolmogorov-Smirnov (KS) test.
This test compares the empirical cumulative distribution functions (ECDFs) of two
independent samples, `xs` and `ys`, to assess the null hypothesis that they
are drawn from the same continuous distribution.
Parameters:
- `xs` (seq of numbers): The first sample.
- `ys` (seq of numbers): The second sample.
- `opts` (map, optional): Options map:
- `:method` (keyword, optional): Specifies the calculation method for the p-value.
- `:exact`: Attempts an exact calculation (suitable for small samples, sensitive to ties). Default if `nx * ny < 10000`.
- `:approximate`: Uses the asymptotic Kolmogorov distribution (suitable for larger samples). Default otherwise.
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): Tests if the distributions differ (ECDFs are different).
- `:right`: Tests if `xs` is stochastically greater than `ys` (ECDF(xs) is below ECDF(ys)).
- `:left`: Tests if `xs` is stochastically smaller than `ys` (ECDF(xs) is above ECDF(ys)).
- `:distinct?` (keyword or boolean, default `:ties`): How to handle duplicate values (ties).
- `:ties` (default): Includes all points. Passes information about ties to the `:exact` calculation method. Accuracy depends on the exact method's tie handling.
- `:jitter`: Adds a small amount of random noise to break ties before comparison. A practical approach if exact tie handling is complex or not required.
- `true`: Applies `distinct` to `xs` and `ys` separately before combining. May not resolve all ties between the combined samples.
- `false`: Uses the data as-is, without attempting to handle ties explicitly (may lead to less accurate p-values, especially with the exact method).
- `:correct?` (boolean, default `true`): Apply continuity correction when using the `:exact` calculation method for a more accurate p-value especially for smaller sample sizes.
Returns a map containing:
- `:nx`: Number of observations in `xs` (after `:distinct?` processing if applicable).
- `:ny`: Number of observations in `ys` (after `:distinct?` processing if applicable).
- `:n`: Effective sample size used for asymptotic calculation (`nx*ny / (nx+ny)`).
- `:dp`: Maximum positive difference (ECDF(xs) - ECDF(ys)).
- `:dn`: Maximum positive difference (ECDF(ys) - ECDF(xs)).
- `:d`: The KS test statistic (max absolute difference: `max(dp, dn)`).
- `:stat`: The specific statistic used for p-value calculation (`d`, `dp`, or `dn` for exact; scaled version for approximate).
- `:KS`: Alias for `:stat`.
- `:p-value`: The p-value associated with the test statistic and `:sides`.
- `:sides`: The alternative hypothesis side used.
- `:method`: The calculation method used (`:exact` or `:approximate`).
Note on Ties: The KS test is strictly defined for continuous distributions where ties have zero probability.
The presence of ties in sample data affects the p-value calculation. The `:distinct?` option provides ways to manage this, with `:jitter` being a common pragmatic choice.(kullback-leibler-divergence [vs1 vs2])(kullback-leibler-divergence vs1 vs2)Kullback-Leibler divergence of two sequences.
Kullback-Leibler divergence of two sequences.
(kurtosis vs)(kurtosis vs typ)Calculates the kurtosis of vs, a measure of the tailedness or peakedness of a distribution compared to a normal distribution.
Several kurtosis definitions are supported through the typ argument, ranging from moment-based estimators to robust, quantile- or trimmed-mean-based estimators. Different types use different algorithms and have different expected values under normality (0 or 3).
Parameters:
vs (sequence of numbers): Input data.typ (keyword or sequence): Kurtosis measure to calculate. Defaults to :G2. One of:
:G2 (default): sample excess kurtosis based on the fourth standardized moment, as implemented by Apache Commons Math Kurtosis. Expected value 0 for a normal distribution.:g2 or :excess: an alternative sample excess kurtosis, obtained from :G2 by inverting its finite-sample bias correction. Expected value 0 for a normal distribution.:kurt: the classical kurtosis definition where normal is 3, calculated as :g2 + 3.:b2: another excess kurtosis variant, obtained by applying an additional finite-sample correction factor to :kurt. Expected value 0 for a normal distribution.:geary: Geary's g, a robust measure calculated as mean-absolute-deviation / population-stddev. Expected value for normal is sqrt(2/pi) ≈ 0.798, lower values indicate leptokurtosis.:moors: Moors' robust kurtosis measure based on octiles, centered so that the expected value for normal is 0.:crow: Crow-Siddiqui robust kurtosis measure based on quantiles, centered so that the expected value for normal is 0. The sequence form [:crow alpha beta] sets the quantile parameters alpha and beta.:hogg: Hogg's robust kurtosis measure based on trimmed means, centered so that the expected value for normal is 0. The sequence form [:hogg alpha beta] sets the trimming parameters alpha and beta.:l-kurtosis: L-kurtosis (τ₄), the ratio of the fourth L-moment (λ₄) to the second L-moment (λ₂, L-scale), a robust measure. Calculated directly using l-moment with :ratio? set to true. Expected value for a normal distribution is approximately 0.1226.For the excess-kurtosis variants (:G2, :g2, :excess, :b2 and the centered robust measures), positive values indicate a leptokurtic distribution (heavier tails, more peaked than normal), negative values indicate a platykurtic distribution (lighter tails, flatter than normal), and values near 0 suggest kurtosis similar to a normal distribution.
Returns the calculated kurtosis as a double.
See also kurtosis-test, bonett-seier-test, skewness, normality-test, jarque-bera-test, l-moment, moment.
Calculates the kurtosis of `vs`, a measure of the tailedness or peakedness of a distribution compared to a normal distribution. Several kurtosis definitions are supported through the `typ` argument, ranging from moment-based estimators to robust, quantile- or trimmed-mean-based estimators. Different types use different algorithms and have different expected values under normality (`0` or `3`). Parameters: - `vs` (sequence of numbers): Input data. - `typ` (keyword or sequence): Kurtosis measure to calculate. Defaults to `:G2`. One of: - `:G2` (default): sample excess kurtosis based on the fourth standardized moment, as implemented by Apache Commons Math `Kurtosis`. Expected value `0` for a normal distribution. - `:g2` or `:excess`: an alternative sample excess kurtosis, obtained from `:G2` by inverting its finite-sample bias correction. Expected value `0` for a normal distribution. - `:kurt`: the classical kurtosis definition where normal is `3`, calculated as `:g2 + 3`. - `:b2`: another excess kurtosis variant, obtained by applying an additional finite-sample correction factor to `:kurt`. Expected value `0` for a normal distribution. - `:geary`: Geary's g, a robust measure calculated as `mean-absolute-deviation / population-stddev`. Expected value for normal is `sqrt(2/pi) ≈ 0.798`, lower values indicate leptokurtosis. - `:moors`: Moors' robust kurtosis measure based on octiles, centered so that the expected value for normal is `0`. - `:crow`: Crow-Siddiqui robust kurtosis measure based on quantiles, centered so that the expected value for normal is `0`. The sequence form `[:crow alpha beta]` sets the quantile parameters `alpha` and `beta`. - `:hogg`: Hogg's robust kurtosis measure based on trimmed means, centered so that the expected value for normal is `0`. The sequence form `[:hogg alpha beta]` sets the trimming parameters `alpha` and `beta`. - `:l-kurtosis`: L-kurtosis (τ₄), the ratio of the fourth L-moment (λ₄) to the second L-moment (λ₂, L-scale), a robust measure. Calculated directly using [[l-moment]] with `:ratio?` set to `true`. Expected value for a normal distribution is approximately `0.1226`. For the excess-kurtosis variants (`:G2`, `:g2`, `:excess`, `:b2` and the centered robust measures), positive values indicate a leptokurtic distribution (heavier tails, more peaked than normal), negative values indicate a platykurtic distribution (lighter tails, flatter than normal), and values near `0` suggest kurtosis similar to a normal distribution. Returns the calculated kurtosis as a double. See also [[kurtosis-test]], [[bonett-seier-test]], [[skewness]], [[normality-test]], [[jarque-bera-test]], [[l-moment]], [[moment]].
(kurtosis-test xs)(kurtosis-test xs params)(kurtosis-test xs kurt {:keys [sides type] :or {sides :two-sided type :kurt}})Performs a test for normality based on sample kurtosis.
This test assesses the null hypothesis that the data comes from a normally distributed population by checking if the sample kurtosis significantly deviates from the kurtosis expected under normality (approximately 3).
The test works by:
:type, default :kurt).Z that more closely follows a
standard normal distribution under the null hypothesis, especially for
smaller sample sizes.Parameters:
xs (seq of numbers): The sample data.kurt (double, optional): A pre-calculated kurtosis value. If omitted, it's calculated from xs.params (map, optional): Options map:
:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): The population kurtosis is different from normal.:one-sided-greater: The population kurtosis is greater than normal (leptokurtic).:one-sided-less: The population kurtosis is less than normal (platykurtic).:type (keyword, default :kurt): The type of kurtosis to calculate if kurt is not provided. See kurtosis for options (e.g., :kurt, :G2, :g2).Returns a map containing:
:Z: The final test statistic, approximately standard normal under H0.:stat: Alias for :Z.:p-value: The p-value associated with Z and the specified :sides.:kurtosis: The sample kurtosis value used in the test (either provided or calculated).See also skewness-test, normality-test, jarque-bera-test, bonett-seier-test.
Performs a test for normality based on sample kurtosis.
This test assesses the null hypothesis that the data comes from a normally
distributed population by checking if the sample kurtosis significantly deviates
from the kurtosis expected under normality (approximately 3).
The test works by:
1. Calculating the sample kurtosis (type configurable via `:type`, default `:kurt`).
2. Standardizing the difference between the sample kurtosis and the expected
kurtosis under normality using the theoretical standard error.
3. Applying a further transformation (e.g., Anscombe-Glynn/D'Agostino) to this standardized
score to yield a final test statistic `Z` that more closely follows a
standard normal distribution under the null hypothesis, especially for
smaller sample sizes.
Parameters:
- `xs` (seq of numbers): The sample data.
- `kurt` (double, optional): A pre-calculated kurtosis value. If omitted, it's calculated from `xs`.
- `params` (map, optional): Options map:
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): The population kurtosis is different from normal.
- `:one-sided-greater`: The population kurtosis is greater than normal (leptokurtic).
- `:one-sided-less`: The population kurtosis is less than normal (platykurtic).
- `:type` (keyword, default `:kurt`): The type of kurtosis to calculate if `kurt` is not provided. See [[kurtosis]] for options (e.g., `:kurt`, `:G2`, `:g2`).
Returns a map containing:
- `:Z`: The final test statistic, approximately standard normal under H0.
- `:stat`: Alias for `:Z`.
- `:p-value`: The p-value associated with `Z` and the specified `:sides`.
- `:kurtosis`: The sample kurtosis value used in the test (either provided or calculated).
See also [[skewness-test]], [[normality-test]], [[jarque-bera-test]], [[bonett-seier-test]].(l-moment vs order)(l-moment vs order {:keys [s t sorted? ratio?] :or {s 0 t 0} :as opts})Calculates the L-moment, TL-moment (trimmed L-moment), or (T)L-moment ratio of vs for a given order.
L-moments are summary statistics for describing the shape of a probability distribution, computed as linear combinations of the expected order statistics of the sample. Unlike conventional moments, they exist whenever the mean of the distribution exists, are more robust to outliers, and suffer less from bias in small samples. Trimming (:s, :t) further excludes extreme order statistics, yielding TL-moments, which remain well-defined even for distributions without a finite mean.
Parameters:
vs (sequence of numbers): Input data.order (long): The order of the L-moment. Order 0 always returns 1.0.opts (map, optional):
:s (long) - number of smallest (left) values trimmed from the sample. Defaults to 0.:t (long) - number of largest (right) values trimmed from the sample. Defaults to 0.:sorted? (boolean) - set to true when vs is already sorted ascending, to skip re-sorting. Defaults to false.:ratio? (boolean) - when true, returns the (T)L-moment ratio, i.e. the L-moment of order normalized by the second L-moment, instead of the raw L-moment. Defaults to false.Returns the computed (T)L-moment or (T)L-moment ratio as a double.
Calculates the L-moment, TL-moment (trimmed L-moment), or (T)L-moment ratio of `vs` for a given `order`. L-moments are summary statistics for describing the shape of a probability distribution, computed as linear combinations of the expected order statistics of the sample. Unlike conventional moments, they exist whenever the mean of the distribution exists, are more robust to outliers, and suffer less from bias in small samples. Trimming (`:s`, `:t`) further excludes extreme order statistics, yielding TL-moments, which remain well-defined even for distributions without a finite mean. Parameters: - `vs` (sequence of numbers): Input data. - `order` (long): The order of the L-moment. Order `0` always returns `1.0`. - `opts` (map, optional): - `:s` (long) - number of smallest (left) values trimmed from the sample. Defaults to `0`. - `:t` (long) - number of largest (right) values trimmed from the sample. Defaults to `0`. - `:sorted?` (boolean) - set to `true` when `vs` is already sorted ascending, to skip re-sorting. Defaults to `false`. - `:ratio?` (boolean) - when `true`, returns the (T)L-moment ratio, i.e. the L-moment of `order` normalized by the second L-moment, instead of the raw L-moment. Defaults to `false`. Returns the computed (T)L-moment or (T)L-moment ratio as a double. See also [[moment]], [[variance]], [[skewness]].
(l-variation vs)Calculates the coefficient of L-variation (L-CV) of vs.
This is a robust analogue of the ordinary coefficient of variation variation: instead of the ratio of the standard deviation to the mean, it is the ratio of the second L-moment (a measure of scale, see l-moment) to the mean.
Parameters:
vs (sequence of numbers): Input data.Returns the L-CV as a double.
Calculates the coefficient of L-variation (L-CV) of `vs`. This is a robust analogue of the ordinary coefficient of variation [[variation]]: instead of the ratio of the standard deviation to the mean, it is the ratio of the second L-moment (a measure of scale, see [[l-moment]]) to the mean. Parameters: - `vs` (sequence of numbers): Input data. Returns the L-CV as a double. See also [[l-moment]], [[variation]], [[mean]].
Count equal values in both seqs. Alias for [[count==]]
Count equal values in both seqs. Alias for [[count==]]
(L1 [vs1 vs2-or-val])(L1 vs1 vs2-or-val)Calculates the L1 distance (Manhattan or City Block distance) between two sequences or a sequence and a constant value.
The L1 distance is the sum of the absolute differences between corresponding elements.
Parameters:
vs1 (sequence of numbers): The first sequence.vs2-or-val (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated L1 distance as a double.
Calculates the L1 distance (Manhattan or City Block distance) between two sequences or a sequence and a constant value. The L1 distance is the sum of the absolute differences between corresponding elements. Parameters: - `vs1` (sequence of numbers): The first sequence. - `vs2-or-val` (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated L1 distance as a double. See also [[L2]], [[L2sq]], [[LInf]], [[mae]] (Mean Absolute Error).
(L2 [vs1 vs2-or-val])(L2 vs1 vs2-or-val)Calculates the L2 distance (Euclidean distance) between two sequences or a sequence and a constant value.
This is the standard straight-line distance between two points (vectors) in Euclidean space.
It is the square root of the L2sq distance.
Parameters:
vs1 (sequence of numbers): The first sequence.vs2-or-val (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated L2 distance as a double.
Calculates the L2 distance (Euclidean distance) between two sequences or a sequence and a constant value. This is the standard straight-line distance between two points (vectors) in Euclidean space. It is the square root of the [[L2sq]] distance. Parameters: - `vs1` (sequence of numbers): The first sequence. - `vs2-or-val` (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated L2 distance as a double. See also [[L1]], [[L2sq]], [[LInf]], [[rmse]] (Root Mean Squared Error).
(L2sq [vs1 vs2-or-val])(L2sq vs1 vs2-or-val)Calculates the Squared Euclidean distance between two sequences or a sequence and a constant value.
This is the sum of the squared differences between corresponding elements.
It is equivalent to the rss (Residual Sum of Squares).
Parameters:
vs1 (sequence of numbers): The first sequence.vs2-or-val (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated Squared Euclidean distance as a double.
See also L1, L2, LInf, rss (Residual Sum of Squares), mse (Mean Squared Error).
Calculates the Squared Euclidean distance between two sequences or a sequence and a constant value. This is the sum of the squared differences between corresponding elements. It is equivalent to the [[rss]] (Residual Sum of Squares). Parameters: - `vs1` (sequence of numbers): The first sequence. - `vs2-or-val` (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated Squared Euclidean distance as a double. See also [[L1]], [[L2]], [[LInf]], [[rss]] (Residual Sum of Squares), [[mse]] (Mean Squared Error).
(levene-test xss)(levene-test xss
{:keys [sides statistic scorediff]
:or {sides :one-sided-greater statistic mean scorediff m/abs}})Performs Levene's test for homogeneity of variances across two or more groups.
Levene's test assesses the null hypothesis that the variances of the groups are equal. It calculates an ANOVA on the absolute deviations of the data points from their group center (mean by default).
Parameters:
xss (sequence of sequences): A collection where each element is a sequence representing a group of observations.params (map, optional): Options map with the following keys:
:sides (keyword, default :one-sided-greater): Alternative hypothesis side for the F-test.
Possible values: :one-sided-greater, :one-sided-less, :two-sided.:statistic (fn, default mean): Function to calculate the center of each group (e.g., mean, median). Using median results in the Brown-Forsythe test.:scorediff (fn, default [[abs]]): Function applied to the difference between each data point and its group center (e.g., [[abs]], [[sq]]).Returns a map containing:
:W: The Levene test statistic (which is an F-statistic).:stat: Alias for :W.:p-value: The p-value for the test.:df: Degrees of freedom for the F-statistic ([DFt, DFe]).:n: Sequence of sample sizes for each group.:SSt: Sum of squares between groups (treatment).:SSe: Sum of squares within groups (error).:DFt: Degrees of freedom between groups.:DFe: Degrees of freedom within groups.:MSt: Mean square between groups.:MSe: Mean square within groups.:sides: Test side used.See also brown-forsythe-test.
Performs Levene's test for homogeneity of variances across two or more groups.
Levene's test assesses the null hypothesis that the variances of the groups are equal.
It calculates an ANOVA on the absolute deviations of the data points from their group
center (mean by default).
Parameters:
- `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations.
- `params` (map, optional): Options map with the following keys:
- `:sides` (keyword, default `:one-sided-greater`): Alternative hypothesis side for the F-test.
Possible values: `:one-sided-greater`, `:one-sided-less`, `:two-sided`.
- `:statistic` (fn, default [[mean]]): Function to calculate the center of each group (e.g., [[mean]], [[median]]). Using [[median]] results in the Brown-Forsythe test.
- `:scorediff` (fn, default [[abs]]): Function applied to the difference between each data point and its group center (e.g., [[abs]], [[sq]]).
Returns a map containing:
- `:W`: The Levene test statistic (which is an F-statistic).
- `:stat`: Alias for `:W`.
- `:p-value`: The p-value for the test.
- `:df`: Degrees of freedom for the F-statistic ([DFt, DFe]).
- `:n`: Sequence of sample sizes for each group.
- `:SSt`: Sum of squares between groups (treatment).
- `:SSe`: Sum of squares within groups (error).
- `:DFt`: Degrees of freedom between groups.
- `:DFe`: Degrees of freedom within groups.
- `:MSt`: Mean square between groups.
- `:MSe`: Mean square within groups.
- `:sides`: Test side used.
See also [[brown-forsythe-test]].(LInf [vs1 vs2-or-val])(LInf vs1 vs2-or-val)Calculates the L-infinity distance (Chebyshev distance) between two sequences or a sequence and a constant value.
The Chebyshev distance is the maximum absolute difference between corresponding elements.
Parameters:
vs1 (sequence of numbers): The first sequence.vs2-or-val (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated L-infinity distance as a double.
Calculates the L-infinity distance (Chebyshev distance) between two sequences or a sequence and a constant value. The Chebyshev distance is the maximum absolute difference between corresponding elements. Parameters: - `vs1` (sequence of numbers): The first sequence. - `vs2-or-val` (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated L-infinity distance as a double. See also [[L1]], [[L2]], [[L2sq]].
(logmean xs)(logmean xs
{:keys [tol max-iters method]
:or {tol 1.0E-15 max-iters 1000 method :integral}})Calculates the generalized logarithmic mean of a sequence of positive numbers.
The logarithmic mean generalizes the two-argument logarithmic mean L(x,y) = (x-y)/(ln(x)-ln(y))
to n arguments. For n=1 the single value is returned as-is; for n=2 the classical
two-argument formula is used; for n>=3 one of two methods is applied.
Parameters:
xs - a sequence of positive numbers (length n >= 1)opts - optional map of configuration keys:
:method - algorithm to use, one of :integral (default) or :mean-value
(aliases :divided, :divided-differences); :integral uses the integral
representation of the generalized log-mean; :mean-value uses divided differences:tol - convergence tolerance for the :integral series expansion (default 1.0e-15):max-iters - maximum number of series iterations for the :integral method (default 1000)Returns the generalized logarithmic mean as a double. Returns ##NaN for an empty sequence.
All values in xs must be strictly positive.
Note 1: :mean-value can be unstable for large number of entries (n >= 100) or when differences are very small.
Note 2: :mean-value and :integral are two different interpretations (definitions) and produce different results.
See also mean, [[geometric-mean]], [[harmonic-mean]].
Generalized integral method is made with Opus 4.8
Calculates the generalized logarithmic mean of a sequence of positive numbers.
The logarithmic mean generalizes the two-argument logarithmic mean `L(x,y) = (x-y)/(ln(x)-ln(y))`
to `n` arguments. For `n=1` the single value is returned as-is; for `n=2` the classical
two-argument formula is used; for `n>=3` one of two methods is applied.
Parameters:
- `xs` - a sequence of positive numbers (length `n >= 1`)
- `opts` - optional map of configuration keys:
- `:method` - algorithm to use, one of `:integral` (default) or `:mean-value`
(aliases `:divided`, `:divided-differences`); `:integral` uses the integral
representation of the generalized log-mean; `:mean-value` uses divided differences
- `:tol` - convergence tolerance for the `:integral` series expansion (default `1.0e-15`)
- `:max-iters` - maximum number of series iterations for the `:integral` method (default `1000`)
Returns the generalized logarithmic mean as a `double`. Returns `##NaN` for an empty sequence.
All values in `xs` must be strictly positive.
Note 1: `:mean-value` can be unstable for large number of entries (`n >= 100`) or when differences are very small.
Note 2: `:mean-value` and `:integral` are two different interpretations (definitions) and produce different results.
See also [[mean]], [[geometric-mean]], [[harmonic-mean]].
Generalized integral method is made with Opus 4.8(mad-extent vs)Calculates the median of vs together with its -/+ median absolute deviation (MAD) extent.
Parameters:
vs (sequence of numbers): Input data.Returns a 3-element vector [(m/- median mad), (m/+ median mad), median].
See also median, median-absolute-deviation, stddev-extent, sem-extent.
Calculates the median of `vs` together with its `-/+` median absolute deviation (MAD) extent. Parameters: - `vs` (sequence of numbers): Input data. Returns a 3-element vector `[(m/- median mad), (m/+ median mad), median]`. See also [[median]], [[median-absolute-deviation]], [[stddev-extent]], [[sem-extent]].
(mae [vs1 vs2-or-val])(mae vs1 vs2-or-val)(mae vs1 vs2-or-val weights)Calculates the Mean Absolute Error (MAE) between two sequences or a sequence and constant value.
MAE is a measure of the difference between two sequences of values. It quantifies the average magnitude of the errors, without considering their direction.
Parameters:
vs1 (sequence of numbers): The first sequence (often the observed or true values).vs2-or-val (sequence of numbers or single number): The second sequence
(often the predicted or reference values), or a single number to compare
against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated Mean Absolute Error as a double.
Note: MAE is less sensitive to large outliers than metrics like Mean Squared Error (MSE) because it uses the absolute value of differences rather than the squared difference.
See also me (Mean Error), mse (Mean Squared Error), rmse (Root Mean Squared Error).
Calculates the Mean Absolute Error (MAE) between two sequences or a sequence and constant value. MAE is a measure of the difference between two sequences of values. It quantifies the average magnitude of the errors, without considering their direction. Parameters: - `vs1` (sequence of numbers): The first sequence (often the observed or true values). - `vs2-or-val` (sequence of numbers or single number): The second sequence (often the predicted or reference values), or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated Mean Absolute Error as a double. Note: MAE is less sensitive to large outliers than metrics like Mean Squared Error (MSE) because it uses the absolute value of differences rather than the squared difference. See also [[me]] (Mean Error), [[mse]] (Mean Squared Error), [[rmse]] (Root Mean Squared Error).
(mape [vs1 vs2-or-val])(mape vs1 vs2-or-val)(mape vs1 vs2-or-val weights)Calculates the Mean Absolute Percentage Error (MAPE) between two sequences or a sequence and a constant value.
MAPE is a measure of prediction accuracy of a forecasting method, for example in time series analysis. It is calculated as the average of the absolute percentage errors.
Parameters:
vs1 (sequence of numbers): The first sequence (conventionally, the actual or true values).vs2-or-val (sequence of numbers or single number): The second sequence
(conventionally, the predicted or reference values), or a single number to
compare against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated Mean Absolute Percentage Error as a double.
Note: MAPE is scale-independent and useful for comparing performance across
different datasets. However, it is undefined if any of the actual values (x_i)
are zero, and can be skewed by small actual values.
See also me (Mean Error), mae (Mean Absolute Error), mse (Mean Squared Error), rmse (Root Mean Squared Error).
Calculates the Mean Absolute Percentage Error (MAPE) between two sequences or a sequence and a constant value. MAPE is a measure of prediction accuracy of a forecasting method, for example in time series analysis. It is calculated as the average of the absolute percentage errors. Parameters: - `vs1` (sequence of numbers): The first sequence (conventionally, the actual or true values). - `vs2-or-val` (sequence of numbers or single number): The second sequence (conventionally, the predicted or reference values), or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated Mean Absolute Percentage Error as a double. Note: MAPE is scale-independent and useful for comparing performance across different datasets. However, it is undefined if any of the actual values (`x_i`) are zero, and can be skewed by small actual values. See also [[me]] (Mean Error), [[mae]] (Mean Absolute Error), [[mse]] (Mean Squared Error), [[rmse]] (Root Mean Squared Error).
(maximum vs)Finds the largest value in a sequence of numbers.
Accepts either a double-array (handled with an optimized, array-specific path) or any other sequence of numbers.
Parameters:
vs (sequence of numbers or double-array): Input data.Returns the maximum value as a double. Throws an exception when vs is empty.
Finds the largest value in a sequence of numbers. Accepts either a `double-array` (handled with an optimized, array-specific path) or any other sequence of numbers. Parameters: - `vs` (sequence of numbers or `double-array`): Input data. Returns the maximum value as a double. Throws an exception when `vs` is empty. See also [[minimum]], [[extent]].
(mcc ct)(mcc group1 group2)Calculates the Matthews Correlation Coefficient (MCC), also known as the Phi coefficient, for a 2x2 contingency table or binary classification outcomes.
MCC is a measure of the quality of binary classifications. It is a balanced measure which can be used even if the classes are of very different sizes. Its value ranges from -1 to +1.
The function can be called in two ways:
With two sequences group1 and group2:
The function will automatically construct a 2x2 contingency table from
the unique values in the sequences (assuming they represent two binary
variables). The mapping of values to table cells (e.g., what corresponds
to TP, TN, FP, FN) depends on how contingency-table orders the unique values.
For direct control over which cell is which, use the contingency table input.
With a contingency table: The contingency table can be provided as:
[row-index, column-index] tuples and values are counts
(e.g., {[0 0] TP, [0 1] FP, [1 0] FN, [1 1] TN}). This is the output format
of contingency-table with two inputs.[[TP FP] [FN TN]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of binary outcomes/categories.group2 (sequence): The second sequence of binary outcomes/categories.
Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed 2x2 contingency table.Returns the calculated Matthews Correlation Coefficient as a double.
Note: The implementation uses marginal sums from the contingency table, which is mathematically equivalent to the standard formula but avoids potential division by zero in the denominator product if any marginal sum is zero.
See also contingency-table, contingency-2x2-measures, binary-measures-all.
Calculates the Matthews Correlation Coefficient (MCC), also known as the Phi coefficient,
for a 2x2 contingency table or binary classification outcomes.
MCC is a measure of the quality of binary classifications. It is a balanced
measure which can be used even if the classes are of very different sizes.
Its value ranges from -1 to +1.
- A coefficient of +1 represents a perfect prediction.
- 0 represents a prediction no better than random.
- -1 represents a perfect inverse prediction.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a 2x2 contingency table from
the unique values in the sequences (assuming they represent two binary
variables). The mapping of values to table cells (e.g., what corresponds
to TP, TN, FP, FN) depends on how `contingency-table` orders the unique values.
For direct control over which cell is which, use the contingency table input.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] TP, [0 1] FP, [1 0] FN, [1 1] TN}`). This is the output format
of [[contingency-table]] with two inputs.
- A sequence of sequences representing the rows of the table
(e.g., `[[TP FP] [FN TN]]`). This is equivalent to `rows->contingency-table`.
Parameters:
- `group1` (sequence): The first sequence of binary outcomes/categories.
- `group2` (sequence): The second sequence of binary outcomes/categories.
Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed 2x2 contingency table.
Returns the calculated Matthews Correlation Coefficient as a double.
Note: The implementation uses marginal sums from the contingency table, which
is mathematically equivalent to the standard formula but avoids potential
division by zero in the denominator product if any marginal sum is zero.
See also [[contingency-table]], [[contingency-2x2-measures]], [[binary-measures-all]].(me [vs1 vs2-or-val])(me vs1 vs2-or-val)(me vs1 vs2-or-val weights)Calculates the Mean Error (ME) between two sequences or a sequence and constant value.
Parameters:
vs1 (sequence of numbers): The first sequence.vs2-or-val (sequence of numbers or single number): The second sequence of
numbers, or a single number to compare against each element of vs1.Both sequences (vs1 and vs2) must have the same length if both are sequences.
If vs2-or-val is a single number, it is compared element-wise to vs1.
Returns the calculated Mean Error as a double.
Note: Positive ME indicates that vs1 values tend to be greater than vs2 values
on average, while negative ME indicates vs1 values tend to be smaller. ME can be
influenced by the magnitude of errors and their signs. It does not directly measure
the magnitude of the typical error due to potential cancellation of positive and
negative differences.
See also mae (Mean Absolute Error), mse (Mean Squared Error), rmse (Root Mean Squared Error).
Calculates the Mean Error (ME) between two sequences or a sequence and constant value. Parameters: - `vs1` (sequence of numbers): The first sequence. - `vs2-or-val` (sequence of numbers or single number): The second sequence of numbers, or a single number to compare against each element of `vs1`. Both sequences (`vs1` and `vs2`) must have the same length if both are sequences. If `vs2-or-val` is a single number, it is compared element-wise to `vs1`. Returns the calculated Mean Error as a double. Note: Positive ME indicates that `vs1` values tend to be greater than `vs2` values on average, while negative ME indicates `vs1` values tend to be smaller. ME can be influenced by the magnitude of errors and their signs. It does not directly measure the magnitude of the typical error due to potential cancellation of positive and negative differences. See also [[mae]] (Mean Absolute Error), [[mse]] (Mean Squared Error), [[rmse]] (Root Mean Squared Error).
(mean vs)(mean vs weights)Calculates the arithmetic mean (average) of a sequence vs.
If weights are provided, calculates the weighted arithmetic mean.
Parameters:
vs: Sequence of numbers.weights (optional): Sequence of non-negative weights corresponding to vs.
Must have the same count as vs.Returns the calculated mean as a double.
Calculates the arithmetic mean (average) of a sequence `vs`. If `weights` are provided, calculates the weighted arithmetic mean. Parameters: - `vs`: Sequence of numbers. - `weights` (optional): Sequence of non-negative weights corresponding to `vs`. Must have the same count as `vs`. Returns the calculated mean as a double. See also [[geomean]], [[harmean]], [[powmean]], [[median]].
(mean-absolute-deviation vs)(mean-absolute-deviation vs center)Calculates the Mean Absolute Deviation of a sequence vs.
MeanAD is a measure of the variability of a univariate sample of quantitative data. It is defined as the mean of the absolute deviations from a central point, typically the data's mean.
MeanAD = mean(|X_i - center|)
Parameters:
vs: Sequence of numbers.center (optional, double): The central point from which to calculate deviations.
If nil or not provided, the arithmetic mean of vs is used as the center.Returns the calculated Mean Absolute Deviation as a double.
Unlike median-absolute-deviation, which uses the median of absolute deviations
from the median, the Mean Absolute Deviation uses the mean of absolute deviations
from the mean (or specified center). This makes it more sensitive to outliers
than median-absolute-deviation but less sensitive than the standard deviation.
See also median-absolute-deviation, stddev, mean.
Calculates the Mean Absolute Deviation of a sequence `vs`. MeanAD is a measure of the variability of a univariate sample of quantitative data. It is defined as the mean of the absolute deviations from a central point, typically the data's mean. `MeanAD = mean(|X_i - center|)` Parameters: - `vs`: Sequence of numbers. - `center` (optional, double): The central point from which to calculate deviations. If `nil` or not provided, the arithmetic [[mean]] of `vs` is used as the center. Returns the calculated Mean Absolute Deviation as a double. Unlike [[median-absolute-deviation]], which uses the median of absolute deviations from the median, the Mean Absolute Deviation uses the mean of absolute deviations from the mean (or specified center). This makes it more sensitive to outliers than [[median-absolute-deviation]] but less sensitive than the standard deviation. See also [[median-absolute-deviation]], [[stddev]], [[mean]].
(means-ratio [group1 group2])(means-ratio group1 group2)(means-ratio group1 group2 adjusted?)Calculates the ratio of the mean of group1 to the mean of group2.
This is a measure of effect size in the 'Ratio Family', comparing the central tendency of two groups multiplicatively.
Parameters:
group1 (seq of numbers): The first independent sample. The mean of this group is the numerator.group2 (seq of numbers): The second independent sample. The mean of this group is the denominator.adjusted? (boolean, optional): If true, applies a small-sample bias correction to the ratio.
Defaults to false.Returns the calculated ratio of means as a double.
A value greater than 1 indicates that group1 has a larger mean than group2.
A value less than 1 indicates group1 has a smaller mean.
A value close to 1 indicates similar means.
The adjusted? version attempts to provide a less biased estimate of the population
mean ratio, particularly for small sample sizes, by incorporating variances into the calculation
(based on Bickel and Doksum, see also means-ratio-corrected).
See also means-ratio-corrected (which is equivalent to calling this with adjusted? set to true).
Calculates the ratio of the mean of `group1` to the mean of `group2`. This is a measure of effect size in the 'Ratio Family', comparing the central tendency of two groups multiplicatively. Parameters: - `group1` (seq of numbers): The first independent sample. The mean of this group is the numerator. - `group2` (seq of numbers): The second independent sample. The mean of this group is the denominator. - `adjusted?` (boolean, optional): If `true`, applies a small-sample bias correction to the ratio. Defaults to `false`. Returns the calculated ratio of means as a double. A value greater than 1 indicates that `group1` has a larger mean than `group2`. A value less than 1 indicates `group1` has a smaller mean. A value close to 1 indicates similar means. The `adjusted?` version attempts to provide a less biased estimate of the population mean ratio, particularly for small sample sizes, by incorporating variances into the calculation (based on Bickel and Doksum, see also [[means-ratio-corrected]]). See also [[means-ratio-corrected]] (which is equivalent to calling this with `adjusted?` set to `true`).
(means-ratio-corrected [group1 group2])(means-ratio-corrected group1 group2)Calculates a bias-corrected ratio of the mean of group1 to the mean of group2.
This function applies a correction (based on Bickel and Doksum) to the simple
ratio mean(group1) / mean(group2) to reduce bias, particularly for small
sample sizes.
It is equivalent to calling (means-ratio group1 group2 true).
Parameters:
group1 (seq of numbers): The first independent sample. The mean of this group
is the numerator.group2 (seq of numbers): The second independent sample. The mean of this group
is the denominator.Returns the calculated bias-corrected ratio of means as a double.
See also means-ratio (for the simple, uncorrected ratio).
Calculates a bias-corrected ratio of the mean of `group1` to the mean of `group2`. This function applies a correction (based on Bickel and Doksum) to the simple ratio `mean(group1) / mean(group2)` to reduce bias, particularly for small sample sizes. It is equivalent to calling `(means-ratio group1 group2 true)`. Parameters: - `group1` (seq of numbers): The first independent sample. The mean of this group is the numerator. - `group2` (seq of numbers): The second independent sample. The mean of this group is the denominator. Returns the calculated bias-corrected ratio of means as a double. See also [[means-ratio]] (for the simple, uncorrected ratio).
(median vs)(median vs estimation-strategy)Calculates median of a sequence vs.
An optional estimation-strategy keyword can be provided to specify the
method used for estimating the quantile, particularly how interpolation is
handled when the desired quantile falls between data points in the sorted
sequence.
Available estimation-strategy values:
:legacy (Default): The original method used in Apache Commons Math.:r1 through :r9: Correspond to the nine quantile estimation algorithms
recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using np or (n+1)p) and how it interpolates between points.For detailed mathematical descriptions of each estimation strategy, refer to the Apache Commons Math Percentile documentation.
Calculates median of a sequence `vs`.
An optional `estimation-strategy` keyword can be provided to specify the
method used for estimating the quantile, particularly how interpolation is
handled when the desired quantile falls between data points in the sorted
sequence.
Available `estimation-strategy` values:
- `:legacy` (Default): The original method used in Apache Commons Math.
- `:r1` through `:r9`: Correspond to the nine quantile estimation algorithms
recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using `np` or `(n+1)p`) and how it interpolates between points.
For detailed mathematical descriptions of each estimation strategy, refer to
the [Apache Commons Math Percentile documentation](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html).
See also [[quantile]], [[median-3]](median-3 a b c)Median of three values. See median.
Median of three values. See [[median]].
(median-absolute-deviation vs)(median-absolute-deviation vs center-or-estimation-strategy)(median-absolute-deviation vs center estimation-strategy)Calculates the Median Absolute Deviation (MAD) of a sequence vs.
MAD is a robust measure of the variability of a univariate sample of quantitative data. It is defined as the median of the absolute deviations from the data's median (or a specified center).
MAD = median(|X_i - median(X)|)
Parameters:
vs: Sequence of numbers.center-or-estimation-strategy (optional): The central point from which to calculate deviations or estimation strategy.
If nil or not provided, the median of vs is used as the center. If keyword, it's treated as estimation strategy for median.estimation-strategy (optional, keyword): The estimation strategy to use for
calculating the median(s). This applies to the calculation of the central
value (if center is not provided) and to the final median of the absolute
deviations. See median or quantile for available strategies (e.g.,
:legacy, :r1 through :r9).Returns the calculated MAD as a double.
MAD is less sensitive to outliers than the standard deviation.
See also mean-absolute-deviation, stddev, median, quantile.
Calculates the Median Absolute Deviation (MAD) of a sequence `vs`. MAD is a robust measure of the variability of a univariate sample of quantitative data. It is defined as the median of the absolute deviations from the data's median (or a specified center). `MAD = median(|X_i - median(X)|)` Parameters: - `vs`: Sequence of numbers. - `center-or-estimation-strategy` (optional): The central point from which to calculate deviations or estimation strategy. If `nil` or not provided, the [[median]] of `vs` is used as the center. If keyword, it's treated as estimation strategy for median. - `estimation-strategy` (optional, keyword): The estimation strategy to use for calculating the median(s). This applies to the calculation of the central value (if `center` is not provided) and to the final median of the absolute deviations. See [[median]] or [[quantile]] for available strategies (e.g., `:legacy`, `:r1` through `:r9`). Returns the calculated MAD as a double. MAD is less sensitive to outliers than the standard deviation. See also [[mean-absolute-deviation]], [[stddev]], [[median]], [[quantile]].
(minimum vs)Finds the smallest value in a sequence of numbers.
Accepts either a double-array (handled with an optimized, array-specific path) or any other sequence of numbers.
Parameters:
vs (sequence of numbers or double-array): Input data.Returns the minimum value as a double. Throws an exception when vs is empty.
Finds the smallest value in a sequence of numbers. Accepts either a `double-array` (handled with an optimized, array-specific path) or any other sequence of numbers. Parameters: - `vs` (sequence of numbers or `double-array`): Input data. Returns the minimum value as a double. Throws an exception when `vs` is empty. See also [[maximum]], [[extent]].
(minimum-discrimination-information-test contingency-table-or-xs)(minimum-discrimination-information-test contingency-table-or-xs params)Minimum discrimination information test, a power divergence test for lambda -1.0
Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Minimum discrimination information test, a power divergence test for `lambda` -1.0
Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(mode vs)(mode vs method)(mode vs method opts)Find the value that appears most often in a dataset vs.
If multiple values share the same highest frequency (or estimated density/histogram peak),
this function returns only the first one encountered during processing. The specific
mode returned in case of a tie is not guaranteed to be stable. Use modes if
you need all tied modes.
For samples potentially drawn from a continuous distribution, several estimation
methods are provided via the method argument:
:histogram: Calculates the mode based on the peak of a histogram constructed from vs.
Uses interpolation within the bin with the highest frequency.
Accepts options via opts, primarily :bins to control histogram
construction (see histogram).:pearson: Estimates the mode using Pearson's second skewness coefficient
formula: mode ≈ 3 * median - 2 * mean. Accepts :estimation-strategy
in opts for median calculation (see median).:kde: Estimates the mode by finding the original data point in vs
with the highest estimated probability density, based on Kernel Density
Estimation (KDE). Accepts KDE options in opts like :kernel, :bandwidth,
etc. (passed to fastmath.kernel.density/kernel-density).:default (or when method is omitted): Finds the exact value that occurs
most frequently in vs. Suitable for discrete data.The optional opts map provides method-specific configuration.
See also modes (returns all modes) and wmode (for weighted data).
Find the value that appears most often in a dataset `vs`. If multiple values share the same highest frequency (or estimated density/histogram peak), this function returns only the *first* one encountered during processing. The specific mode returned in case of a tie is not guaranteed to be stable. Use [[modes]] if you need all tied modes. For samples potentially drawn from a continuous distribution, several estimation methods are provided via the `method` argument: * `:histogram`: Calculates the mode based on the peak of a histogram constructed from `vs`. Uses interpolation within the bin with the highest frequency. Accepts options via `opts`, primarily `:bins` to control histogram construction (see [[histogram]]). * `:pearson`: Estimates the mode using Pearson's second skewness coefficient formula: `mode ≈ 3 * median - 2 * mean`. Accepts `:estimation-strategy` in `opts` for median calculation (see [[median]]). * `:kde`: Estimates the mode by finding the original data point in `vs` with the highest estimated probability density, based on Kernel Density Estimation (KDE). Accepts KDE options in `opts` like `:kernel`, `:bandwidth`, etc. (passed to `fastmath.kernel.density/kernel-density`). * `:default` (or when `method` is omitted): Finds the exact value that occurs most frequently in `vs`. Suitable for discrete data. The optional `opts` map provides method-specific configuration. See also [[modes]] (returns all modes) and [[wmode]] (for weighted data).
(modes vs)(modes vs method)(modes vs method opts)Find the values that appear most often in a dataset vs.
Returns sequence with all most appearing values. For the default method (discrete data), modes are sorted in increasing order.
For samples potentially drawn from a continuous distribution, simply finding the
most frequent exact value might not be meaningful. Several estimation methods
are provided via the method argument:
:histogram: Calculates the mode(s) based on the peak(s) of a histogram constructed
from vs. Uses interpolation within the bin(s) with the highest frequency.
Accepts options via opts, primarily :bins to control histogram
construction (see histogram).:pearson: Estimates the mode using Pearson's second skewness coefficient
formula: mode ≈ 3 * median - 2 * mean. Accepts :estimation-strategy
in opts for median calculation (see median). Returns a single estimated mode.:kde: Estimates the mode(s) by finding the original data points in vs
with the highest estimated probability density, based on Kernel Density
Estimation (KDE). Accepts KDE options in opts like :kernel, :bandwidth,
etc. (passed to fastmath.kernel.density/kernel-density).:default (or when method is omitted): Finds the exact value(s) that occur
most frequently in vs. Suitable for discrete data.The optional opts map provides method-specific configuration.
See also mode (returns only the first mode) and wmodes (for weighted data).
Find the values that appear most often in a dataset `vs`. Returns sequence with all most appearing values. For the default method (discrete data), modes are sorted in increasing order. For samples potentially drawn from a continuous distribution, simply finding the most frequent exact value might not be meaningful. Several estimation methods are provided via the `method` argument: * `:histogram`: Calculates the mode(s) based on the peak(s) of a histogram constructed from `vs`. Uses interpolation within the bin(s) with the highest frequency. Accepts options via `opts`, primarily `:bins` to control histogram construction (see [[histogram]]). * `:pearson`: Estimates the mode using Pearson's second skewness coefficient formula: `mode ≈ 3 * median - 2 * mean`. Accepts `:estimation-strategy` in `opts` for median calculation (see [[median]]). Returns a single estimated mode. * `:kde`: Estimates the mode(s) by finding the original data points in `vs` with the highest estimated probability density, based on Kernel Density Estimation (KDE). Accepts KDE options in `opts` like `:kernel`, `:bandwidth`, etc. (passed to `fastmath.kernel.density/kernel-density`). * `:default` (or when `method` is omitted): Finds the exact value(s) that occur most frequently in `vs`. Suitable for discrete data. The optional `opts` map provides method-specific configuration. See also [[mode]] (returns only the first mode) and [[wmodes]] (for weighted data).
(modified-power-transformation xs)(modified-power-transformation xs lambda)(modified-power-transformation xs lambda alpha)Applies a modified power transformation (Bickel and Doksum) to a data.
Applies a modified power transformation (Bickel and Doksum) to a data.
(moment vs)(moment vs order)(moment vs order {:keys [absolute? center mean? normalize?] :or {mean? true}})Calculates the statistical moment of vs of the given order (default: 2.0).
This is a general building block used to compute variance-like, skewness-like, and kurtosis-like statistics by combining a few switches: whether deviations are taken as absolute values, around which center, whether the result is averaged, and whether it is normalized by the standard deviation. For example, order=2.0 with default options gives the population variance, order=3.0 with :normalize? set to true gives a skewness-like statistic, and order=4.0 with :normalize? set to true gives a kurtosis-like statistic.
Parameters:
vs (sequence of numbers): Input data.order (double): Power to raise the (optionally absolute) deviations to. Defaults to 2.0.opts (map, optional):
:absolute? (boolean) - when true, deviations are taken as absolute values before raising to order. Defaults to false.:mean? (boolean) - when true, averages the deviations (a proper moment); when false, returns their plain sum. Defaults to true.:center (double) - the center to compute deviations from. Defaults to nil, meaning the mean of vs is used.:normalize? (boolean) - when true, divides the result by the standard deviation of vs raised to order. Defaults to false.Returns the computed moment as a double.
Calculates the statistical moment of `vs` of the given `order` (default: `2.0`). This is a general building block used to compute variance-like, skewness-like, and kurtosis-like statistics by combining a few switches: whether deviations are taken as absolute values, around which center, whether the result is averaged, and whether it is normalized by the standard deviation. For example, `order=2.0` with default options gives the population variance, `order=3.0` with `:normalize?` set to `true` gives a skewness-like statistic, and `order=4.0` with `:normalize?` set to `true` gives a kurtosis-like statistic. Parameters: - `vs` (sequence of numbers): Input data. - `order` (double): Power to raise the (optionally absolute) deviations to. Defaults to `2.0`. - `opts` (map, optional): - `:absolute?` (boolean) - when `true`, deviations are taken as absolute values before raising to `order`. Defaults to `false`. - `:mean?` (boolean) - when `true`, averages the deviations (a proper moment); when `false`, returns their plain sum. Defaults to `true`. - `:center` (double) - the center to compute deviations from. Defaults to `nil`, meaning the mean of `vs` is used. - `:normalize?` (boolean) - when `true`, divides the result by the standard deviation of `vs` raised to `order`. Defaults to `false`. Returns the computed moment as a double. See also [[variance]], [[skewness]], [[kurtosis]].
(mse [vs1 vs2-or-val])(mse vs1 vs2-or-val)(mse vs1 vs2-or-val weights)Calculates the Mean Squared Error (MSE) between two sequences or a sequence and a constant value.
MSE is a measure of the quality of an estimator or predictor. It quantifies the average of the squared differences between corresponding elements of the input sequences.
Parameters:
vs1 (sequence of numbers): The first sequence (often the observed or true values).vs2-or-val (sequence of numbers or single number): The second sequence
(often the predicted or reference values), or a single number to compare
against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated Mean Squared Error as a double.
Note: MSE penalizes larger errors more heavily than smaller errors because the
errors are squared. This makes it sensitive to outliers. It is the average
of the rss (Residual Sum of Squares). Its square root is the rmse.
See also rss (Residual Sum of Squares), rmse (Root Mean Squared Error),
me (Mean Error), mae (Mean Absolute Error), r2 (Coefficient of Determination).
Calculates the Mean Squared Error (MSE) between two sequences or a sequence and a constant value. MSE is a measure of the quality of an estimator or predictor. It quantifies the average of the squared differences between corresponding elements of the input sequences. Parameters: - `vs1` (sequence of numbers): The first sequence (often the observed or true values). - `vs2-or-val` (sequence of numbers or single number): The second sequence (often the predicted or reference values), or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated Mean Squared Error as a double. Note: MSE penalizes larger errors more heavily than smaller errors because the errors are squared. This makes it sensitive to outliers. It is the average of the [[rss]] (Residual Sum of Squares). Its square root is the [[rmse]]. See also [[rss]] (Residual Sum of Squares), [[rmse]] (Root Mean Squared Error), [[me]] (Mean Error), [[mae]] (Mean Absolute Error), [[r2]] (Coefficient of Determination).
(multiclass-auc classes scores)(multiclass-auc classes
scores
{:keys [average metric weighted?]
:or {average mean metric :roc weighted? false}})Calculates AUC for a multiclass problem using a one-vs-rest strategy.
Each class is treated as the positive class in turn, and its AUC is computed against all remaining classes. The final result is aggregated across classes according to the chosen averaging strategy.
Parameters:
classes - a sequence of true class labels (any comparable values).scores - either a sequence of score vectors (one per instance, shared across all classes)
or a map from class label to a sequence of per-instance scores for that class.opts - (optional) a map of options:
:metric - the curve to integrate over (default: :roc); supported values:
:roc - ROC curve (:fpr vs :tpr):pr - Precision-Recall curve (:recall vs :precision):det - Detection Error Tradeoff curve (:fpr vs :fnr)[x-axis y-axis] of keywords or metric functions accepted by auc:average - how to aggregate per-class AUC values (default: mean); supported values:
mean) - macro average, applies the function to per-class AUC scores:micro - micro average, concatenates all classes before computing a single AUCnil - returns a map of {class auc} with no aggregation:weighted? - when true, passes per-class instance counts as weights to :average function (default: false); ignored when :average is :micro or nilReturns a single aggregated AUC double when :average is a function or :micro,
or a map of {class auc} when :average is nil. NaN per-class AUC values are replaced with 0.0.
See also auc, auc-roc, binary-measures-thr.
Calculates AUC for a multiclass problem using a one-vs-rest strategy.
Each class is treated as the positive class in turn, and its AUC is computed against all remaining classes.
The final result is aggregated across classes according to the chosen averaging strategy.
Parameters:
- `classes` - a sequence of true class labels (any comparable values).
- `scores` - either a sequence of score vectors (one per instance, shared across all classes)
or a map from class label to a sequence of per-instance scores for that class.
- `opts` - (optional) a map of options:
- `:metric` - the curve to integrate over (default: `:roc`); supported values:
- `:roc` - ROC curve (`:fpr` vs `:tpr`)
- `:pr` - Precision-Recall curve (`:recall` vs `:precision`)
- `:det` - Detection Error Tradeoff curve (`:fpr` vs `:fnr`)
- a two-element vector `[x-axis y-axis]` of keywords or metric functions accepted by [[auc]]
- `:average` - how to aggregate per-class AUC values (default: `mean`); supported values:
- a function (e.g. `mean`) - macro average, applies the function to per-class AUC scores
- `:micro` - micro average, concatenates all classes before computing a single AUC
- `nil` - returns a map of `{class auc}` with no aggregation
- `:weighted?` - when `true`, passes per-class instance counts as weights to `:average` function (default: `false`); ignored when `:average` is `:micro` or `nil`
Returns a single aggregated AUC double when `:average` is a function or `:micro`,
or a map of `{class auc}` when `:average` is `nil`. `NaN` per-class AUC values are replaced with `0.0`.
See also [[auc]], [[auc-roc]], [[binary-measures-thr]].(multiclass-measure actual prediction)(multiclass-measure
actual
prediction
{:keys [average metric weighted? beta]
:or {average mean metric :f1-score weighted? false beta 1.0}})Calculates an average of selected metric for multiclass binary classification results using one vs the rest strategy. Possible variants are macro, weighted and micro.
Possible metrics are the same as in binary-measures-all.
Options:
:average - average function, nil or :micro (default: mean):metric - measure to calculate (default: :f1-score).:weighted? - weighted average variant (default: false):beta - beta for :f-beta (default: 0.5)Calculates an average of selected metric for multiclass binary classification results using one vs the rest strategy. Possible variants are `macro`, `weighted` and `micro`. Possible metrics are the same as in [[binary-measures-all]]. Options: - `:average` - average function, `nil` or `:micro` (default: `mean`) - `:metric` - measure to calculate (default: `:f1-score`). - `:weighted?` - `weighted` average variant (default: `false`) - `:beta` - beta for `:f-beta` (default: `0.5`)
(multinomial-likelihood-ratio-test contingency-table-or-xs)(multinomial-likelihood-ratio-test contingency-table-or-xs params)Multinomial likelihood ratio test, a power divergence test for lambda 0.0
Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Multinomial likelihood ratio test, a power divergence test for `lambda` 0.0
Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(mutual-information group1 group2)(mutual-information group1 group2 log-base)Calculates the mutual information I(X;Y) between two sequences.
Mutual information quantifies the amount of information (in nats, by default) obtained about one variable through observing the other. It is 0.0 when the two variables are (empirically) independent, and is defined as H(group1) + H(group2) - H(group1, group2).
Parameters:
group1, group2 (sequences): Two sequences of (typically categorical) observations of the same length, paired by index.log-base (double, optional): The logarithm base used, see entropy. Defaults to e.Returns the calculated mutual information as a double. Always >= 0.0, and <= min(H(group1), H(group2)).
See also entropy, joint-entropy, theils-u (a normalized version of mutual information).
Calculates the mutual information I(X;Y) between two sequences. Mutual information quantifies the amount of information (in nats, by default) obtained about one variable through observing the other. It is `0.0` when the two variables are (empirically) independent, and is defined as `H(group1) + H(group2) - H(group1, group2)`. Parameters: - `group1`, `group2` (sequences): Two sequences of (typically categorical) observations of the same length, paired by index. - `log-base` (double, optional): The logarithm base used, see [[entropy]]. Defaults to `e`. Returns the calculated mutual information as a double. Always `>= 0.0`, and `<= min(H(group1), H(group2))`. See also [[entropy]], [[joint-entropy]], [[theils-u]] (a normalized version of mutual information).
(neyman-modified-chisq-test contingency-table-or-xs)(neyman-modified-chisq-test contingency-table-or-xs params)Neyman modifield chi square test, a power divergence test for lambda -2.0
Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Neyman modifield chi square test, a power divergence test for `lambda` -2.0
Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(normality-test xs)(normality-test xs params)(normality-test xs skew kurt {:keys [sides] :or {sides :one-sided-greater}})Performs the D'Agostino-Pearson K² omnibus test for normality.
This test combines the results of the skewness and kurtosis tests to provide an overall assessment of whether the sample data deviates from a normal distribution in terms of either asymmetry or peakedness/tailedness.
The test works by:
skewness-test.kurtosis-test.Parameters:
xs (seq of numbers): The sample data.skew (double, optional): A pre-calculated skewness value (type :g1 used by default in underlying test).kurt (double, optional): A pre-calculated kurtosis value (type :kurt used by default in underlying test).params (map, optional): Options map:
:sides (keyword, default :one-sided-greater): Specifies the side(s) of the
Chi-squared(2) distribution used for p-value calculation.
:one-sided-greater (default and standard): Tests if K² is significantly large,
indicating departure from normality in skewness, kurtosis, or both.:one-sided-less: Tests if the K² statistic is significantly small.:two-sided: Tests if the K² statistic is extreme in either tail.Returns a map containing:
:Z: The calculated K² omnibus test statistic (labeled :Z for consistency,
though it follows Chi-squared(2)).:stat: Alias for :Z.:p-value: The p-value associated with the K² statistic and :sides.:skewness: The sample skewness value used (either provided or calculated).:kurtosis: The sample kurtosis value used (either provided or calculated).See also skewness-test, kurtosis-test, jarque-bera-test.
Performs the D'Agostino-Pearson K² omnibus test for normality.
This test combines the results of the skewness and kurtosis tests to provide
an overall assessment of whether the sample data deviates from a normal distribution
in terms of either asymmetry or peakedness/tailedness.
The test works by:
1. Calculating a normalized test statistic (Z₁) for skewness using [[skewness-test]].
2. Calculating a normalized test statistic (Z₂) for kurtosis using [[kurtosis-test]].
3. Combining these into an omnibus statistic: K² = Z₁² + Z₂².
4. Under the null hypothesis that the data comes from a normal distribution,
K² approximately follows a Chi-squared distribution with 2 degrees of freedom.
Parameters:
- `xs` (seq of numbers): The sample data.
- `skew` (double, optional): A pre-calculated skewness value (type `:g1` used by default in underlying test).
- `kurt` (double, optional): A pre-calculated kurtosis value (type `:kurt` used by default in underlying test).
- `params` (map, optional): Options map:
- `:sides` (keyword, default `:one-sided-greater`): Specifies the side(s) of the
Chi-squared(2) distribution used for p-value calculation.
- `:one-sided-greater` (default and standard): Tests if K² is significantly large,
indicating departure from normality in skewness, kurtosis, or both.
- `:one-sided-less`: Tests if the K² statistic is significantly small.
- `:two-sided`: Tests if the K² statistic is extreme in either tail.
Returns a map containing:
- `:Z`: The calculated K² omnibus test statistic (labeled `:Z` for consistency,
though it follows Chi-squared(2)).
- `:stat`: Alias for `:Z`.
- `:p-value`: The p-value associated with the K² statistic and `:sides`.
- `:skewness`: The sample skewness value used (either provided or calculated).
- `:kurtosis`: The sample kurtosis value used (either provided or calculated).
See also [[skewness-test]], [[kurtosis-test]], [[jarque-bera-test]].(omega-sq [group1 group2])(omega-sq group1 group2)(omega-sq group1 group2 degrees-of-freedom)Calculates Omega squared (ω²), an effect size measure for the simple linear regression of group1 on group2.
Omega squared estimates the proportion of variance in the dependent variable (group1) that is accounted for by the independent variable (group2) in the population. It is considered a less biased alternative to r2-determination.
Parameters:
group1 (seq of numbers): The dependent variable.group2 (seq of numbers): The independent variable. Must have the same length as group1.degrees-of-freedom (double, optional): The degrees of freedom for the regression model. Defaults to 1.0, which is standard for simple linear regression and used in the 2-arity version. Providing a different value allows calculating ω² for cases with multiple predictors if the sums of squares are computed for the overall model.Returns the calculated Omega squared value as a double. The value typically ranges from 0.0 to 1.0.
Interpretation:
group2 explains none of the variance in group1 in the population.group2 perfectly explains the variance in group1 in the population.Note: While often presented in the context of ANOVA, this implementation applies the formula to the sums of squares obtained from a simple linear regression between the two sequences. The 3-arity version allows specifying a custom degrees of freedom for regression, which might be relevant for calculating overall $\omega^2$ in multiple regression contexts (where degrees-of-freedom would be the number of predictors).
See also eta-sq (Eta-squared, often based on $R^2$), epsilon-sq (another adjusted R²-like measure), r2-determination (R-squared).
Calculates Omega squared (ω²), an effect size measure for the simple linear regression of `group1` on `group2`. Omega squared estimates the proportion of variance in the dependent variable (`group1`) that is accounted for by the independent variable (`group2`) in the population. It is considered a less biased alternative to [[r2-determination]]. Parameters: - `group1` (seq of numbers): The dependent variable. - `group2` (seq of numbers): The independent variable. Must have the same length as `group1`. - `degrees-of-freedom` (double, optional): The degrees of freedom for the regression model. Defaults to 1.0, which is standard for simple linear regression and used in the 2-arity version. Providing a different value allows calculating ω² for cases with multiple predictors if the sums of squares are computed for the overall model. Returns the calculated Omega squared value as a double. The value typically ranges from 0.0 to 1.0. Interpretation: - 0.0 indicates that `group2` explains none of the variance in `group1` in the population. - 1.0 indicates that `group2` perfectly explains the variance in `group1` in the population. Note: While often presented in the context of ANOVA, this implementation applies the formula to the sums of squares obtained from a simple linear regression between the two sequences. The 3-arity version allows specifying a custom degrees of freedom for regression, which might be relevant for calculating overall $\omega^2$ in multiple regression contexts (where `degrees-of-freedom` would be the number of predictors). See also [[eta-sq]] (Eta-squared, often based on $R^2$), [[epsilon-sq]] (another adjusted R²-like measure), [[r2-determination]] (R-squared).
(one-way-anova-test xss)(one-way-anova-test xss {:keys [sides] :or {sides :one-sided-greater}})Performs a one-way analysis of variance (ANOVA) test.
ANOVA tests the null hypothesis that the means of two or more independent groups are equal. It assumes that the data within each group are normally distributed and have equal variances.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence
representing a group of observations.params (map, optional): Options map with the following key:
:sides (keyword, default :one-sided-greater): Alternative hypothesis side for the F-test.
Possible values: :one-sided-greater, :one-sided-less, :two-sided.Returns a map containing:
:F: The F-statistic for the test.:stat: Alias for :F.:p-value: The p-value for the test.:df: Degrees of freedom for the F-statistic ([DFt, DFe]).:n: Sequence of sample sizes for each group.:SSt: Sum of squares between groups (treatment).:SSe: Sum of squares within groups (error).:DFt: Degrees of freedom between groups.:DFe: Degrees of freedom within groups.:MSt: Mean square between groups.:MSe: Mean square within groups.:sides: Test side used.Performs a one-way analysis of variance (ANOVA) test.
ANOVA tests the null hypothesis that the means of two or more independent groups
are equal. It assumes that the data within each group are normally distributed
and have equal variances.
Parameters:
- `xss` (sequence of sequences): A collection where each element is a sequence
representing a group of observations.
- `params` (map, optional): Options map with the following key:
- `:sides` (keyword, default `:one-sided-greater`): Alternative hypothesis side for the F-test.
Possible values: `:one-sided-greater`, `:one-sided-less`, `:two-sided`.
Returns a map containing:
- `:F`: The F-statistic for the test.
- `:stat`: Alias for `:F`.
- `:p-value`: The p-value for the test.
- `:df`: Degrees of freedom for the F-statistic ([DFt, DFe]).
- `:n`: Sequence of sample sizes for each group.
- `:SSt`: Sum of squares between groups (treatment).
- `:SSe`: Sum of squares within groups (error).
- `:DFt`: Degrees of freedom between groups.
- `:DFe`: Degrees of freedom within groups.
- `:MSt`: Mean square between groups.
- `:MSe`: Mean square within groups.
- `:sides`: Test side used.(outer-fence-extent vs)(outer-fence-extent vs estimation-strategy)Calculates the lower and upper outer fence thresholds (LOF and UOF) of vs, together with its median.
The outer fences are wider outlier thresholds than the inner fences (see inner-fence-extent), computed from Q1 and Q3, the 25th and 75th percentiles, and IQR = Q3 - Q1:
Q1 - 3*IQR.Q3 + 3*IQR.Values beyond the outer fences are considered extreme (far) outliers, in contrast to the milder outliers flagged by the inner fences.
Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a 3-element vector [LOF UOF median].
See also inner-fence-extent, adjacent-values, iqr, percentile-extent.
Calculates the lower and upper outer fence thresholds (LOF and UOF) of `vs`, together with its median. The outer fences are wider outlier thresholds than the inner fences (see [[inner-fence-extent]]), computed from `Q1` and `Q3`, the 25th and 75th percentiles, and `IQR = Q3 - Q1`: - LOF is the lower outer fence, `Q1 - 3*IQR`. - UOF is the upper outer fence, `Q3 + 3*IQR`. Values beyond the outer fences are considered extreme (far) outliers, in contrast to the milder outliers flagged by the inner fences. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a 3-element vector `[LOF UOF median]`. See also [[inner-fence-extent]], [[adjacent-values]], [[iqr]], [[percentile-extent]].
(outliers vs)(outliers vs estimation-strategy)(outliers vs q1 q3)Finds outliers in vs, defined as values falling outside the inner fences.
Let Q1 and Q3 be the 25th and 75th percentiles and IQR = Q3 - Q1. A value is considered an outlier when it is below the lower inner fence, Q1 - 1.5*IQR, or above the upper inner fence, Q3 + 1.5*IQR.
Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.q1, q3 (doubles): Precomputed first and third quartiles, used instead of computing them from vs.Returns a lazy sequence of the values from vs that lie outside the inner fences, in their original order.
See also remove-outliers, inner-fence-extent, adjacent-values, iqr.
Finds outliers in `vs`, defined as values falling outside the inner fences. Let `Q1` and `Q3` be the 25th and 75th percentiles and `IQR = Q3 - Q1`. A value is considered an outlier when it is below the lower inner fence, `Q1 - 1.5*IQR`, or above the upper inner fence, `Q3 + 1.5*IQR`. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. - `q1`, `q3` (doubles): Precomputed first and third quartiles, used instead of computing them from `vs`. Returns a lazy sequence of the values from `vs` that lie outside the inner fences, in their original order. See also [[remove-outliers]], [[inner-fence-extent]], [[adjacent-values]], [[iqr]].
(p-overlap [group1 group2])(p-overlap group1 group2)(p-overlap group1
group2
{:keys [kde bandwidth min-iterations steps]
:or {kde :gaussian min-iterations 3 steps 500}})Calculates the overlapping index between the estimated distributions of two samples using Kernel Density Estimation (KDE).
This function estimates the probability density function (PDF) for group1 and group2 using KDE and then calculates the area of overlap between the two estimated PDFs. The area of overlap is the integral of the minimum of the two density functions.
Parameters:
group1 (seq of numbers): The first sample.group2 (seq of numbers): The second sample.opts (map, optional): Options map for KDE and integration:
:kde (keyword, default :gaussian): The kernel function to use for KDE. See fastmath.kernel.density/kernel-density+ for options.:bandwidth (double, optional): The bandwidth for KDE. If omitted, it is automatically estimated.:min-iterations (long, default 3): Minimum number of iterations for Romberg integration.:steps (long, default 500): Number of steps (subintervals) for numerical integration over the relevant range.Returns the calculated overlapping index as a double, representing the area of overlap between the two estimated distributions. A value closer to 1 indicates greater overlap, while a value closer to 0 indicates less overlap.
This measure quantifies the degree to which two distributions share common values and can be seen as a measure of similarity.
Calculates the overlapping index between the estimated distributions of two samples using Kernel Density Estimation (KDE). This function estimates the probability density function (PDF) for `group1` and `group2` using KDE and then calculates the area of overlap between the two estimated PDFs. The area of overlap is the integral of the minimum of the two density functions. Parameters: - `group1` (seq of numbers): The first sample. - `group2` (seq of numbers): The second sample. - `opts` (map, optional): Options map for KDE and integration: - `:kde` (keyword, default `:gaussian`): The kernel function to use for KDE. See `fastmath.kernel.density/kernel-density+` for options. - `:bandwidth` (double, optional): The bandwidth for KDE. If omitted, it is automatically estimated. - `:min-iterations` (long, default 3): Minimum number of iterations for Romberg integration. - `:steps` (long, default 500): Number of steps (subintervals) for numerical integration over the relevant range. Returns the calculated overlapping index as a double, representing the area of overlap between the two estimated distributions. A value closer to 1 indicates greater overlap, while a value closer to 0 indicates less overlap. This measure quantifies the degree to which two distributions share common values and can be seen as a measure of similarity.
(p-value stat)(p-value distribution stat)(p-value distribution stat sides)Calculates the p-value for a given test statistic based on a reference probability distribution.
The p-value represents the probability of observing a test statistic as extreme as,
or more extreme than, the provided stat, assuming the null hypothesis is true
(where the null hypothesis implies stat follows the given distribution).
Parameters:
distribution (distribution object, optional): The probability distribution object
(from fastmath.random) that the test statistic follows under the null
hypothesis. Defaults to the standard normal distribution (fastmath.random/default-normal)
if omitted.stat (double): The observed value of the test statistic.sides (keyword, optional): Specifies the type of alternative hypothesis and
how 'extremeness' is defined. Defaults to :two-sided.
:two-sided or :both: Alternative hypothesis is that the true parameter is
different from the null value (tests for extremeness in either tail).
Calculates 2 * min(CDF(stat), CCDF(stat)) (adjusted for discrete).:one-sided-greater or :right: Alternative hypothesis is that the true
parameter is greater than the null value (tests for extremeness in the right tail).
Calculates CCDF(stat) (adjusted for discrete).:one-sided-less, :left, or :one-sided: Alternative hypothesis is that the true
parameter is less than the null value (tests for extremeness in the left tail).
Calculates CDF(stat).Note: For discrete distributions, a continuity correction (stat - 1 for CCDF calculations)
is applied when calculating right-tail or two-tail probabilities involving the
upper tail. This ensures the probability mass at the statistic value is correctly
accounted for.
Returns the calculated p-value (a double between 0.0 and 1.0).
Calculates the p-value for a given test statistic based on a reference probability distribution.
The p-value represents the probability of observing a test statistic as extreme as,
or more extreme than, the provided `stat`, assuming the null hypothesis is true
(where the null hypothesis implies `stat` follows the given `distribution`).
Parameters:
- `distribution` (distribution object, optional): The probability distribution object
(from `fastmath.random`) that the test statistic follows under the null
hypothesis. Defaults to the standard normal distribution (`fastmath.random/default-normal`)
if omitted.
- `stat` (double): The observed value of the test statistic.
- `sides` (keyword, optional): Specifies the type of alternative hypothesis and
how 'extremeness' is defined. Defaults to `:two-sided`.
- `:two-sided` or `:both`: Alternative hypothesis is that the true parameter is
different from the null value (tests for extremeness in either tail).
Calculates `2 * min(CDF(stat), CCDF(stat))` (adjusted for discrete).
- `:one-sided-greater` or `:right`: Alternative hypothesis is that the true
parameter is greater than the null value (tests for extremeness in the right tail).
Calculates `CCDF(stat)` (adjusted for discrete).
- `:one-sided-less`, `:left`, or `:one-sided`: Alternative hypothesis is that the true
parameter is less than the null value (tests for extremeness in the left tail).
Calculates `CDF(stat)`.
Note: For discrete distributions, a continuity correction (`stat - 1` for CCDF calculations)
is applied when calculating right-tail or two-tail probabilities involving the
upper tail. This ensures the probability mass *at* the statistic value is correctly
accounted for.
Returns the calculated p-value (a double between 0.0 and 1.0).(pacf data)(pacf data lags)Calculates the Partial Autocorrelation Function (PACF) for a given time series data.
The PACF measures the linear dependence between a time series and its lagged values after removing the effects of the intermediate lags. It helps identify the direct relationship at each lag and is used to determine the order of autoregressive (AR) components in time series models (e.g., ARIMA).
Parameters:
data (seq of numbers): The time series data.lags (long, optional): The maximum lag for which to calculate the PACF. If omitted, calculates PACF for lags from 0 up to (dec (count data)).Returns a sequence of doubles representing the partial autocorrelation coefficients for the specified lags. The value at lag 0 is always 0.0.
Calculates the Partial Autocorrelation Function (PACF) for a given time series `data`. The PACF measures the linear dependence between a time series and its lagged values *after removing* the effects of the intermediate lags. It helps identify the direct relationship at each lag and is used to determine the order of autoregressive (AR) components in time series models (e.g., ARIMA). Parameters: * `data` (seq of numbers): The time series data. * `lags` (long, optional): The maximum lag for which to calculate the PACF. If omitted, calculates PACF for lags from 0 up to `(dec (count data))`. Returns a sequence of doubles representing the partial autocorrelation coefficients for the specified lags. The value at lag 0 is always 0.0. See also [[acf]], [[acf-ci]], [[pacf-ci]].
(pacf-ci data)(pacf-ci data lags)(pacf-ci data lags alpha)Calculates the Partial Autocorrelation Function (PACF) for a time series and provides approximate confidence intervals.
This function computes the PACF of the input time series data for specified lags
(see pacf) and includes approximate confidence intervals around the PACF
estimates. These intervals help determine whether the partial autocorrelation at
a specific lag is statistically significant (i.e., likely non-zero in the population).
Parameters:
data (seq of numbers): The time series data.lags (long, optional): The maximum lag for which to calculate the PACF and CI.
If omitted, calculates for lags up to (dec (count data)).alpha (double, optional): The significance level for the confidence intervals.
Defaults to 0.05 (for a 95% CI).Returns a map containing:
:ci (double): The value of the approximate standard confidence interval bound
for lags > 0. If the absolute value of a PACF
coefficient at lag k > 0 exceeds this value, it is considered statistically significant.:pacf (seq of doubles): The sequence of partial autocorrelation coefficients
at lags from 0 up to lags (calculated using pacf).Calculates the Partial Autocorrelation Function (PACF) for a time series and provides approximate confidence intervals. This function computes the PACF of the input time series `data` for specified lags (see [[pacf]]) and includes approximate confidence intervals around the PACF estimates. These intervals help determine whether the partial autocorrelation at a specific lag is statistically significant (i.e., likely non-zero in the population). Parameters: * `data` (seq of numbers): The time series data. * `lags` (long, optional): The maximum lag for which to calculate the PACF and CI. If omitted, calculates for lags up to `(dec (count data))`. * `alpha` (double, optional): The significance level for the confidence intervals. Defaults to `0.05` (for a 95% CI). Returns a map containing: * `:ci` (double): The value of the approximate standard confidence interval bound for lags > 0. If the absolute value of a PACF coefficient at lag `k > 0` exceeds this value, it is considered statistically significant. * `:pacf` (seq of doubles): The sequence of partial autocorrelation coefficients at lags from 0 up to `lags` (calculated using [[pacf]]). See also [[pacf]], [[acf]], [[acf-ci]].
(pearson-correlation [vs1 vs2])(pearson-correlation vs1 vs2)Calculates the Pearson product-moment correlation coefficient between two sequences.
This function measures the linear relationship between two datasets. The coefficient value ranges from -1.0 (perfect negative linear correlation) to 1.0 (perfect positive linear correlation), with 0.0 indicating no linear correlation.
Parameters:
[vs1 vs2] (sequence of two sequences): A sequence containing the two sequences of numbers.vs1, vs2 (sequences): The two sequences of numbers directly as arguments.Both input sequences must contain only numbers and must have the same length.
Returns the calculated Pearson correlation coefficient as a double. Returns NaN if
either sequence has zero variance (i.e., all elements are the same).
See also correlation (general correlation, defaults to Pearson), spearman-correlation,
kendall-correlation, correlation-matrix.
Calculates the Pearson product-moment correlation coefficient between two sequences. This function measures the linear relationship between two datasets. The coefficient value ranges from -1.0 (perfect negative linear correlation) to 1.0 (perfect positive linear correlation), with 0.0 indicating no linear correlation. Parameters: - `[vs1 vs2]` (sequence of two sequences): A sequence containing the two sequences of numbers. - `vs1`, `vs2` (sequences): The two sequences of numbers directly as arguments. Both input sequences must contain only numbers and must have the same length. Returns the calculated Pearson correlation coefficient as a double. Returns `NaN` if either sequence has zero variance (i.e., all elements are the same). See also [[correlation]] (general correlation, defaults to Pearson), [[spearman-correlation]], [[kendall-correlation]], [[correlation-matrix]].
(pearson-r [group1 group2])(pearson-r group1 group2)Calculates the Pearson r correlation coefficient between two sequences.
This function is an alias for pearson-correlation.
See pearson-correlation for detailed documentation, parameters, and usage examples.
Calculates the Pearson `r` correlation coefficient between two sequences. This function is an alias for [[pearson-correlation]]. See [[pearson-correlation]] for detailed documentation, parameters, and usage examples.
(percentile vs p)(percentile vs p estimation-strategy)Calculates the p-th percentile of a sequence vs.
The percentile p is a value between 0 and 100, inclusive.
An optional estimation-strategy keyword can be provided to specify the
method used for estimating the percentile, particularly how interpolation is
handled when the desired percentile falls between data points in the sorted
sequence.
Available estimation-strategy values:
:legacy (Default): The original method used in Apache Commons Math.:r1 through :r9: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using np or (n+1)p) and how it interpolates between points.For detailed mathematical descriptions of each estimation strategy, refer to the Apache Commons Math Percentile documentation.
See also quantile (which uses a 0.0-1.0 range) and percentiles.
Calculates the p-th percentile of a sequence `vs`. The percentile `p` is a value between 0 and 100, inclusive. An optional `estimation-strategy` keyword can be provided to specify the method used for estimating the percentile, particularly how interpolation is handled when the desired percentile falls between data points in the sorted sequence. Available `estimation-strategy` values: - `:legacy` (Default): The original method used in Apache Commons Math. - `:r1` through `:r9`: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using `np` or `(n+1)p`) and how it interpolates between points. For detailed mathematical descriptions of each estimation strategy, refer to the [Apache Commons Math Percentile documentation](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html). See also [[quantile]] (which uses a 0.0-1.0 range) and [[percentiles]].
(percentile-bc-extent vs)(percentile-bc-extent vs p)(percentile-bc-extent vs p1 p2)(percentile-bc-extent vs p1 p2 estimation-strategy)Return bias corrected percentile range and mean for bootstrap samples. See https://projecteuclid.org/euclid.ss/1032280214
p - calculates extent of bias corrected p and 100-p (default: p=2.5)
Set estimation-strategy to :r7 to get the same result as in R coxed::bca.
Return bias corrected percentile range and mean for bootstrap samples. See https://projecteuclid.org/euclid.ss/1032280214 `p` - calculates extent of bias corrected `p` and `100-p` (default: `p=2.5`) Set `estimation-strategy` to `:r7` to get the same result as in R `coxed::bca`.
(percentile-bca-extent vs)(percentile-bca-extent vs p)(percentile-bca-extent vs p1 p2)(percentile-bca-extent vs p1 p2 estimation-strategy)(percentile-bca-extent vs p1 p2 accel estimation-strategy)Return bias corrected percentile range and mean for bootstrap samples. Also accounts for variance variations throught the accelaration parameter. See https://projecteuclid.org/euclid.ss/1032280214
p - calculates extent of bias corrected p and 100-p (default: p=2.5)
Set estimation-strategy to :r7 to get the same result as in R coxed::bca.
Return bias corrected percentile range and mean for bootstrap samples. Also accounts for variance variations throught the accelaration parameter. See https://projecteuclid.org/euclid.ss/1032280214 `p` - calculates extent of bias corrected `p` and `100-p` (default: `p=2.5`) Set `estimation-strategy` to `:r7` to get the same result as in R `coxed::bca`.
(percentile-extent vs)(percentile-extent vs p)(percentile-extent vs p1 p2)(percentile-extent vs p1 p2 estimation-strategy)Calculates a pair of percentiles of vs together with its median.
By default, computes the p-th and (100-p)-th percentiles, forming a symmetric interval around the median; two independent percentiles p1 and p2 can be given instead.
Parameters:
vs (sequence of numbers): Input data.p (double): Lower percentile, in range [0,100]. The upper percentile is 100-p. Defaults to 25.0.p1, p2 (doubles): Two independent percentiles, in range [0,100], used instead of p/100-p.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a 3-element vector [(percentile vs p1), (percentile vs p2), (median vs)].
See also percentile, median, quantile-extent, pi-extent.
Calculates a pair of percentiles of `vs` together with its median. By default, computes the `p`-th and `(100-p)`-th percentiles, forming a symmetric interval around the median; two independent percentiles `p1` and `p2` can be given instead. Parameters: - `vs` (sequence of numbers): Input data. - `p` (double): Lower percentile, in range `[0,100]`. The upper percentile is `100-p`. Defaults to `25.0`. - `p1`, `p2` (doubles): Two independent percentiles, in range `[0,100]`, used instead of `p`/`100-p`. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a 3-element vector `[(percentile vs p1), (percentile vs p2), (median vs)]`. See also [[percentile]], [[median]], [[quantile-extent]], [[pi-extent]].
(percentiles vs)(percentiles vs ps)(percentiles vs ps estimation-strategy)Calculates the sequence of p-th percentiles of a sequence vs.
Percentiles ps is sequence of values between 0 and 100, inclusive.
An optional estimation-strategy keyword can be provided to specify the
method used for estimating the percentile, particularly how interpolation is
handled when the desired percentile falls between data points in the sorted
sequence.
Available estimation-strategy values:
:legacy (Default): The original method used in Apache Commons Math.:r1 through :r9: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using np or (n+1)p) and how it interpolates between points.For detailed mathematical descriptions of each estimation strategy, refer to the Apache Commons Math Percentile documentation.
See also quantiles (which uses a 0.0-1.0 range) and percentile.
Calculates the sequence of p-th percentiles of a sequence `vs`. Percentiles `ps` is sequence of values between 0 and 100, inclusive. An optional `estimation-strategy` keyword can be provided to specify the method used for estimating the percentile, particularly how interpolation is handled when the desired percentile falls between data points in the sorted sequence. Available `estimation-strategy` values: - `:legacy` (Default): The original method used in Apache Commons Math. - `:r1` through `:r9`: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using `np` or `(n+1)p`) and how it interpolates between points. For detailed mathematical descriptions of each estimation strategy, refer to the [Apache Commons Math Percentile documentation](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html). See also [[quantiles]] (which uses a 0.0-1.0 range) and [[percentile]].
(pi vs)(pi vs size)(pi vs size estimation-strategy)Calculates the Percentile Interval (PI), a symmetric quantile-based credible interval of vs.
Given a target probability mass size, the interval spans the quantiles (1-size)/2 and 1-(1-size)/2, so that size proportion of the data lies within it. Unlike hpdi-extent, this interval is not necessarily the narrowest one covering size, but it is symmetric with respect to probability mass on each tail.
Parameters:
vs (sequence of numbers): Input data.size (double): Target probability content of the interval, in range [0,1]. Defaults to 0.5.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a map of two entries, keyed by the lower and upper bound percentage mapping to the corresponding quantile values.
See also pi-extent (vector form including the median), hpdi-extent, quantile.
Calculates the Percentile Interval (PI), a symmetric quantile-based credible interval of `vs`. Given a target probability mass `size`, the interval spans the quantiles `(1-size)/2` and `1-(1-size)/2`, so that `size` proportion of the data lies within it. Unlike [[hpdi-extent]], this interval is not necessarily the narrowest one covering `size`, but it is symmetric with respect to probability mass on each tail. Parameters: - `vs` (sequence of numbers): Input data. - `size` (double): Target probability content of the interval, in range `[0,1]`. Defaults to `0.5`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a map of two entries, keyed by the lower and upper bound percentage mapping to the corresponding quantile values. See also [[pi-extent]] (vector form including the median), [[hpdi-extent]], [[quantile]].
(pi-extent vs)(pi-extent vs size)(pi-extent vs size estimation-strategy)Calculates the Percentile Interval (PI) of vs together with its median.
Given a target probability mass size, the interval spans the quantiles (1-size)/2 and 1-(1-size)/2. This is the vector-returning counterpart of pi, following the same convention as percentile-extent and quantile-extent.
Parameters:
vs (sequence of numbers): Input data.size (double): Target probability content of the interval, in range [0,1]. Defaults to 0.5.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a 3-element vector [lower-bound upper-bound median].
See also pi, hpdi-extent, quantile-extent.
Calculates the Percentile Interval (PI) of `vs` together with its median. Given a target probability mass `size`, the interval spans the quantiles `(1-size)/2` and `1-(1-size)/2`. This is the vector-returning counterpart of [[pi]], following the same convention as [[percentile-extent]] and [[quantile-extent]]. Parameters: - `vs` (sequence of numbers): Input data. - `size` (double): Target probability content of the interval, in range `[0,1]`. Defaults to `0.5`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a 3-element vector `[lower-bound upper-bound median]`. See also [[pi]], [[hpdi-extent]], [[quantile-extent]].
(pooled-mad groups)(pooled-mad groups const)Calculates a pooled, robust measure of scale across several samples, based on the median absolute deviation (MAD) of their pooled residuals.
Each group is first centered by subtracting its own median, and all the centered groups are then concatenated into a single pooled sample of residuals, whose MAD is computed and scaled by const.
Parameters:
groups (sequence of sequences of numbers): The independent samples to pool.const (double): Scaling constant applied to the MAD of the pooled residuals. Defaults to 1.4826022185056023, the constant that makes MAD a consistent estimator of the standard deviation for normally distributed data, see median-absolute-deviation.Returns the pooled MAD as a double.
See also median-absolute-deviation, pooled-variance, pooled-stddev.
Calculates a pooled, robust measure of scale across several samples, based on the median absolute deviation (MAD) of their pooled residuals. Each group is first centered by subtracting its own median, and all the centered groups are then concatenated into a single pooled sample of residuals, whose MAD is computed and scaled by `const`. Parameters: - `groups` (sequence of sequences of numbers): The independent samples to pool. - `const` (double): Scaling constant applied to the MAD of the pooled residuals. Defaults to `1.4826022185056023`, the constant that makes MAD a consistent estimator of the standard deviation for normally distributed data, see [[median-absolute-deviation]]. Returns the pooled MAD as a double. See also [[median-absolute-deviation]], [[pooled-variance]], [[pooled-stddev]].
(pooled-stddev groups)(pooled-stddev groups method)Calculates the pooled standard deviation of several samples, the square root of pooled-variance.
Parameters:
groups (sequence of sequences of numbers): The independent samples to pool.method (keyword): Pooling method, see pooled-variance for details. Defaults to :unbiased.Returns the pooled standard deviation as a double.
See also pooled-variance, stddev, cohens-d.
Calculates the pooled standard deviation of several samples, the square root of [[pooled-variance]]. Parameters: - `groups` (sequence of sequences of numbers): The independent samples to pool. - `method` (keyword): Pooling method, see [[pooled-variance]] for details. Defaults to `:unbiased`. Returns the pooled standard deviation as a double. See also [[pooled-variance]], [[stddev]], [[cohens-d]].
(pooled-variance groups)(pooled-variance groups method)Calculates the pooled variance of several samples, a weighted combination of their individual variances, used when the samples are assumed to share a common (unknown) variance.
Parameters:
groups (sequence of sequences of numbers): The independent samples to pool.method (keyword): Pooling method. Defaults to :unbiased. One of:
:unbiased (default): each group's variance is weighted by its degrees of freedom n_i - 1, then the weighted sum is divided by the total degrees of freedom sum(n_i) - k, where k is the number of groups. This is the classic unbiased pooled-variance estimator.:biased: same weighted sum of variances as :unbiased, but divided by the total sample size sum(n_i) instead of the total degrees of freedom.:avg: plain, unweighted average of the individual group variances, each group contributing equally regardless of its size.Returns the pooled variance as a double.
See also pooled-stddev, variance, cohens-d.
Calculates the pooled variance of several samples, a weighted combination of their individual variances, used when the samples are assumed to share a common (unknown) variance. Parameters: - `groups` (sequence of sequences of numbers): The independent samples to pool. - `method` (keyword): Pooling method. Defaults to `:unbiased`. One of: - `:unbiased` (default): each group's variance is weighted by its degrees of freedom `n_i - 1`, then the weighted sum is divided by the total degrees of freedom `sum(n_i) - k`, where `k` is the number of groups. This is the classic unbiased pooled-variance estimator. - `:biased`: same weighted sum of variances as `:unbiased`, but divided by the total sample size `sum(n_i)` instead of the total degrees of freedom. - `:avg`: plain, unweighted average of the individual group variances, each group contributing equally regardless of its size. Returns the pooled variance as a double. See also [[pooled-stddev]], [[variance]], [[cohens-d]].
(population-stddev vs)(population-stddev vs mu)Calculates the population (biased) standard deviation of vs.
Computed as the square root of population-variance, i.e. it divides the sum of squared deviations by n rather than n-1. Use this version when vs represents the entire population rather than a sample drawn from it.
Parameters:
vs (sequence of numbers): Input data.mu (double, optional): Precomputed mean of vs. When omitted, the mean is computed from vs.Returns the population standard deviation as a double.
See also stddev, population-variance, population-wstddev.
Calculates the population (biased) standard deviation of `vs`. Computed as the square root of [[population-variance]], i.e. it divides the sum of squared deviations by `n` rather than `n-1`. Use this version when `vs` represents the entire population rather than a sample drawn from it. Parameters: - `vs` (sequence of numbers): Input data. - `mu` (double, optional): Precomputed mean of `vs`. When omitted, the mean is computed from `vs`. Returns the population standard deviation as a double. See also [[stddev]], [[population-variance]], [[population-wstddev]].
(population-variance vs)(population-variance vs mu)Calculates the population (biased) variance of vs.
The mean of the squared deviations from the mean is divided by the number of observations n, unlike the sample variance variance, which divides by n-1 (Bessel's correction). Use this version when vs represents the entire population rather than a sample drawn from it.
Parameters:
vs (sequence of numbers): Input data.mu (double, optional): Precomputed mean of vs. When omitted, the mean is computed from vs.Returns the population variance as a double.
See also variance, population-stddev, population-wvariance.
Calculates the population (biased) variance of `vs`. The mean of the squared deviations from the mean is divided by the number of observations `n`, unlike the sample variance [[variance]], which divides by `n-1` (Bessel's correction). Use this version when `vs` represents the entire population rather than a sample drawn from it. Parameters: - `vs` (sequence of numbers): Input data. - `mu` (double, optional): Precomputed mean of `vs`. When omitted, the mean is computed from `vs`. Returns the population variance as a double. See also [[variance]], [[population-stddev]], [[population-wvariance]].
(population-wstddev vs weights)Calculates the weighted population (biased) standard deviation of vs.
Computed as the square root of population-wvariance, i.e. each value is weighted by the corresponding entry in freqs and the sum of squared deviations is divided by the sum of the weights.
Parameters:
vs (sequence of numbers): Input data.weights (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in vs, same length as vs.Returns the weighted population standard deviation as a double.
See also wstddev, population-wvariance, population-stddev.
Calculates the weighted population (biased) standard deviation of `vs`. Computed as the square root of [[population-wvariance]], i.e. each value is weighted by the corresponding entry in `freqs` and the sum of squared deviations is divided by the sum of the weights. Parameters: - `vs` (sequence of numbers): Input data. - `weights` (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in `vs`, same length as `vs`. Returns the weighted population standard deviation as a double. See also [[wstddev]], [[population-wvariance]], [[population-stddev]].
(population-wvariance vs freqs)Calculates the weighted population (biased) variance of vs.
Each value is weighted by the corresponding entry in freqs, and the weighted mean of the squared deviations from the weighted mean is divided by the sum of the weights. This is the weighted analogue of population-variance; for the unbiased version, dividing by (sum freqs) - 1 instead, see wvariance.
Parameters:
vs (sequence of numbers): Input data.freqs (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in vs, same length as vs.Returns the weighted population variance as a double.
See also wvariance, population-variance, population-wstddev.
Calculates the weighted population (biased) variance of `vs`. Each value is weighted by the corresponding entry in `freqs`, and the weighted mean of the squared deviations from the weighted mean is divided by the sum of the weights. This is the weighted analogue of [[population-variance]]; for the unbiased version, dividing by `(sum freqs) - 1` instead, see [[wvariance]]. Parameters: - `vs` (sequence of numbers): Input data. - `freqs` (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in `vs`, same length as `vs`. Returns the weighted population variance as a double. See also [[wvariance]], [[population-variance]], [[population-wstddev]].
(power-divergence-test contingency-table-or-xs)(power-divergence-test contingency-table-or-xs
{:keys [lambda ci-sides sides p alpha bootstrap-samples
ddof bins]
:or {lambda m/TWO_THIRD
sides :one-sided-greater
ci-sides :two-sided
alpha 0.05
bootstrap-samples 1000
ddof 0}})Performs a power divergence test, which encompasses several common statistical tests like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter. This function can perform either a goodness-of-fit test or a test for independence in a contingency table.
Usage:
Goodness-of-Fit (GOF):
observed-counts (sequence of numbers) and :p (expected probabilities/weights).data (sequence of numbers) and :p (a distribution object).
In this case, a histogram of data is created (controlled by :bins) and
compared against the probability mass/density of the distribution in those bins.Test for Independence:
contingency-table (2D sequence or map format). The :p option is ignored.Options map:
:lambda (double, default: 2/3): Determines the specific test statistic. Common values:
1.0: Pearson Chi-squared test (chisq-test).0.0: G-test / Multinomial Likelihood Ratio test (multinomial-likelihood-ratio-test).-0.5: Freeman-Tukey test (freeman-tukey-test).-1.0: Minimum Discrimination Information test (minimum-discrimination-information-test).-2.0: Neyman Modified Chi-squared test (neyman-modified-chisq-test).2/3: Cressie-Read test (default, cressie-read-test).:p (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a fastmath.random distribution object (for GOF with data). Ignored for independence tests.:alpha (double, default: 0.05): Significance level for confidence intervals.:ci-sides (keyword, default: :two-sided): Sides for bootstrap confidence intervals
(:two-sided, :one-sided-greater, :one-sided-less).:sides (keyword, default: :one-sided-greater): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (:one-sided-greater, :one-sided-less, :two-sided).:bootstrap-samples (long, default: 1000): Number of bootstrap samples for confidence interval estimation.:ddof (long, default: 0): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.:bins (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see histogram), or explicit bin edges for histogram creation.Returns a map containing:
:stat: The calculated power divergence test statistic.:chi2: Alias for :stat.:df: Degrees of freedom for the test.:p-value: The p-value associated with the test statistic.:n: Total number of observations.:estimate: Observed proportions.:expected: Expected counts or proportions under the null hypothesis.:confidence-interval: Bootstrap confidence intervals for the observed proportions.:lambda, :alpha, :sides, :ci-sides: Input options used.:yates, :yates-p-value: Present only for a test for independence on a 2x2 contingency table
(i.e. :df is 1). :yates is the same :lambda-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by min(0.5, |observed-expected|)), matching R's chisq.test(correct=TRUE) and SciPy's
chi2_contingency(correction=True). :yates-p-value is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.Performs a power divergence test, which encompasses several common statistical tests
like Chi-squared, G-test (likelihood ratio), etc., based on the lambda parameter.
This function can perform either a goodness-of-fit test or a test for independence
in a contingency table.
Usage:
1. **Goodness-of-Fit (GOF):**
- Input: `observed-counts` (sequence of numbers) and `:p` (expected probabilities/weights).
- Input: `data` (sequence of numbers) and `:p` (a distribution object).
In this case, a histogram of `data` is created (controlled by `:bins`) and
compared against the probability mass/density of the distribution in those bins.
2. **Test for Independence:**
- Input: `contingency-table` (2D sequence or map format). The `:p` option is ignored.
Options map:
* `:lambda` (double, default: `2/3`): Determines the specific test statistic. Common values:
* `1.0`: Pearson Chi-squared test ([[chisq-test]]).
* `0.0`: G-test / Multinomial Likelihood Ratio test ([[multinomial-likelihood-ratio-test]]).
* `-0.5`: Freeman-Tukey test ([[freeman-tukey-test]]).
* `-1.0`: Minimum Discrimination Information test ([[minimum-discrimination-information-test]]).
* `-2.0`: Neyman Modified Chi-squared test ([[neyman-modified-chisq-test]]).
* `2/3`: Cressie-Read test (default, [[cressie-read-test]]).
* `:p` (seq of numbers or distribution): Expected probabilities/weights (for GOF with counts)
or a `fastmath.random` distribution object (for GOF with data). Ignored for independence tests.
* `:alpha` (double, default: `0.05`): Significance level for confidence intervals.
* `:ci-sides` (keyword, default: `:two-sided`): Sides for bootstrap confidence intervals
(`:two-sided`, `:one-sided-greater`, `:one-sided-less`).
* `:sides` (keyword, default: `:one-sided-greater`): Alternative hypothesis side for the p-value calculation
against the Chi-squared distribution (`:one-sided-greater`, `:one-sided-less`, `:two-sided`).
* `:bootstrap-samples` (long, default: `1000`): Number of bootstrap samples for confidence interval estimation.
* `:ddof` (long, default: `0`): Delta degrees of freedom. Adjustment subtracted from the calculated degrees of freedom.
* `:bins` (number, keyword, or seq): Used only for GOF test against a distribution.
Specifies the number of bins, an estimation method (see [[histogram]]), or explicit bin edges for histogram creation.
Returns a map containing:
- `:stat`: The calculated power divergence test statistic.
- `:chi2`: Alias for `:stat`.
- `:df`: Degrees of freedom for the test.
- `:p-value`: The p-value associated with the test statistic.
- `:n`: Total number of observations.
- `:estimate`: Observed proportions.
- `:expected`: Expected counts or proportions under the null hypothesis.
- `:confidence-interval`: Bootstrap confidence intervals for the observed proportions.
- `:lambda`, `:alpha`, `:sides`, `:ci-sides`: Input options used.
- `:yates`, `:yates-p-value`: Present only for a test for independence on a 2x2 contingency table
(i.e. `:df` is `1`). `:yates` is the same `:lambda`-family statistic recomputed after applying
Yates' continuity correction (each cell's observed count is shifted towards its expected count
by `min(0.5, |observed-expected|)`), matching R's `chisq.test(correct=TRUE)` and SciPy's
`chi2_contingency(correction=True)`. `:yates-p-value` is the corresponding p-value. The
correction is not applied (and these keys are absent) for larger tables or for goodness-of-fit
tests, matching the reference implementations above.(power-transformation xs)(power-transformation xs lambda)(power-transformation xs lambda alpha)Applies a power transformation to a data.
Applies a power transformation to a data.
(powmean vs power)(powmean vs weights power)Calculates the generalized power mean (also known as the Hölder mean) of a sequence vs.
The power mean is a generalization of the Pythagorean means (arithmetic, geometric, harmonic)
and other means like the quadratic mean (RMS). It is defined for a non-zero real number power.
Parameters:
vs: Sequence of numbers. Constraints depend on the power:
power > 0, values should be non-negative.power = 0, values must be positive (reduces to geometric mean).power < 0, values must be positive and non-zero.weights (optional): Sequence of non-negative weights corresponding to vs.
Must have the same count as vs.power (double): The exponent defining the mean.Special Cases:
power = 0: Returns the geomean.power = 1: Returns the arithmetic mean.power = -1: Equivalent to the harmean. (Handled by the general formula)power = 2: Returns the Root Mean Square (RMS) or quadratic mean.power = inf: Returns maximum.power = -inf: Returms minimum.power values 1/3, 0.5, 2, and 3.Returns the calculated power mean as a double.
Calculates the generalized power mean (also known as the Hölder mean) of a sequence `vs`. The power mean is a generalization of the Pythagorean means (arithmetic, geometric, harmonic) and other means like the quadratic mean (RMS). It is defined for a non-zero real number `power`. Parameters: - `vs`: Sequence of numbers. Constraints depend on the `power`: - For `power > 0`, values should be non-negative. - For `power = 0`, values must be positive (reduces to geometric mean). - For `power < 0`, values must be positive and non-zero. - `weights` (optional): Sequence of non-negative weights corresponding to `vs`. Must have the same count as `vs`. - `power` (double): The exponent defining the mean. Special Cases: - `power = 0`: Returns the [[geomean]]. - `power = 1`: Returns the arithmetic [[mean]]. - `power = -1`: Equivalent to the [[harmean]]. (Handled by the general formula) - `power = 2`: Returns the Root Mean Square (RMS) or quadratic mean. - `power = inf`: Returns maximum. - `power = -inf`: Returms minimum. - The implementation includes optimized paths for `power` values 1/3, 0.5, 2, and 3. Returns the calculated power mean as a double. See also [[mean]], [[geomean]], [[harmean]].
(psnr [vs1 vs2-or-val])(psnr vs1 vs2-or-val)(psnr vs1 vs2-or-val max-value)Peak Signal-to-Noise Ratio (PSNR).
PSNR is a measure used to quantify the quality of reconstruction of lossy compression codecs (e.g., for images or video). It is calculated using the Mean Squared Error (MSE) between the original and compressed images/signals. A higher PSNR generally indicates a higher quality signal reconstruction (i.e., less distortion).
Parameters:
vs1 (sequence of numbers): The first sequence (conventionally, the original or reference signal/data).vs2-or-val (sequence of numbers or single number): The second sequence
(conventionally, the reconstructed or noisy signal/data), or a single number
to compare against each element of vs1.max-value (optional, double): The maximum possible value of a sample in the data.
If not provided, the function automatically determines the maximum value present
across both input sequences (vs1 and vs2 if a sequence, or vs1 and the scalar value
if vs2-or-val is a number). Providing an explicit max-value is often more
appropriate based on the data type's theoretical maximum range (e.g., 255 for 8-bit).If vs2-or-val is a sequence, both vs1 and vs2 must have the same length.
Returns the calculated Peak Signal-to-Noise Ratio as a double. Returns -Double/Infinity
if the MSE is zero (perfect match). Returns NaN if MSE is non-positive.
Peak Signal-to-Noise Ratio (PSNR). PSNR is a measure used to quantify the quality of reconstruction of lossy compression codecs (e.g., for images or video). It is calculated using the Mean Squared Error (MSE) between the original and compressed images/signals. A higher PSNR generally indicates a higher quality signal reconstruction (i.e., less distortion). Parameters: - `vs1` (sequence of numbers): The first sequence (conventionally, the original or reference signal/data). - `vs2-or-val` (sequence of numbers or single number): The second sequence (conventionally, the reconstructed or noisy signal/data), or a single number to compare against each element of `vs1`. - `max-value` (optional, double): The maximum possible value of a sample in the data. If not provided, the function automatically determines the maximum value present across both input sequences (`vs1` and `vs2` if a sequence, or `vs1` and the scalar value if `vs2-or-val` is a number). Providing an explicit `max-value` is often more appropriate based on the data type's theoretical maximum range (e.g., 255 for 8-bit). If `vs2-or-val` is a sequence, both `vs1` and `vs2` must have the same length. Returns the calculated Peak Signal-to-Noise Ratio as a double. Returns `-Double/Infinity` if the MSE is zero (perfect match). Returns `NaN` if MSE is non-positive. See also [[mse]], [[rmse]].
(quantile vs q)(quantile vs q estimation-strategy)Calculates the q-th quantile of a sequence vs.
The quantile q is a value between 0.0 and 1.0, inclusive.
An optional estimation-strategy keyword can be provided to specify the
method used for estimating the quantile, particularly how interpolation is
handled when the desired quantile falls between data points in the sorted
sequence.
Available estimation-strategy values:
:legacy (Default): The original method used in Apache Commons Math.:r1 through :r9: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using np or (n+1)p) and how it interpolates between points.For detailed mathematical descriptions of each estimation strategy, refer to the Apache Commons Math Percentile documentation.
See also percentile (which uses a 0-100 range) and quantiles.
Calculates the q-th quantile of a sequence `vs`. The quantile `q` is a value between 0.0 and 1.0, inclusive. An optional `estimation-strategy` keyword can be provided to specify the method used for estimating the quantile, particularly how interpolation is handled when the desired quantile falls between data points in the sorted sequence. Available `estimation-strategy` values: - `:legacy` (Default): The original method used in Apache Commons Math. - `:r1` through `:r9`: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using `np` or `(n+1)p`) and how it interpolates between points. For detailed mathematical descriptions of each estimation strategy, refer to the [Apache Commons Math Percentile documentation](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html). See also [[percentile]] (which uses a 0-100 range) and [[quantiles]].
(quantile-extent vs)(quantile-extent vs q)(quantile-extent vs q1 q2)(quantile-extent vs q1 q2 estimation-strategy)Calculates a pair of quantiles of vs together with its median.
By default, computes the q-th and (1.0-q)-th quantiles, forming a symmetric interval around the median; two independent quantiles q1 and q2 can be given instead.
Parameters:
vs (sequence of numbers): Input data.q (double): Lower quantile, in range [0,1]. The upper quantile is 1.0-q. Defaults to 0.25.q1, q2 (doubles): Two independent quantiles, in range [0,1], used instead of q/1.0-q.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a 3-element vector [(quantile vs q1), (quantile vs q2), (median vs)].
See also quantile, median, percentile-extent, pi-extent.
Calculates a pair of quantiles of `vs` together with its median. By default, computes the `q`-th and `(1.0-q)`-th quantiles, forming a symmetric interval around the median; two independent quantiles `q1` and `q2` can be given instead. Parameters: - `vs` (sequence of numbers): Input data. - `q` (double): Lower quantile, in range `[0,1]`. The upper quantile is `1.0-q`. Defaults to `0.25`. - `q1`, `q2` (doubles): Two independent quantiles, in range `[0,1]`, used instead of `q`/`1.0-q`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a 3-element vector `[(quantile vs q1), (quantile vs q2), (median vs)]`. See also [[quantile]], [[median]], [[percentile-extent]], [[pi-extent]].
(quantiles vs)(quantiles vs qs)(quantiles vs qs estimation-strategy)Calculates the sequence of q-th quantiles of a sequence vs.
Quantiles q is a sequence of values between 0.0 and 1.0, inclusive.
An optional estimation-strategy keyword can be provided to specify the
method used for estimating the quantile, particularly how interpolation is
handled when the desired quantile falls between data points in the sorted
sequence.
Available estimation-strategy values:
:legacy (Default): The original method used in Apache Commons Math.:r1 through :r9: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using np or (n+1)p) and how it interpolates between points.For detailed mathematical descriptions of each estimation strategy, refer to the Apache Commons Math Percentile documentation.
See also percentiles (which uses a 0-100 range) and quantile.
Calculates the sequence of q-th quantiles of a sequence `vs`. Quantiles `q` is a sequence of values between 0.0 and 1.0, inclusive. An optional `estimation-strategy` keyword can be provided to specify the method used for estimating the quantile, particularly how interpolation is handled when the desired quantile falls between data points in the sorted sequence. Available `estimation-strategy` values: - `:legacy` (Default): The original method used in Apache Commons Math. - `:r1` through `:r9`: Correspond to the nine quantile estimation algorithms recommended by Hyndman and Fan (1996). Each strategy differs slightly in how it calculates the index (e.g., using `np` or `(n+1)p`) and how it interpolates between points. For detailed mathematical descriptions of each estimation strategy, refer to the [Apache Commons Math Percentile documentation](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html). See also [[percentiles]] (which uses a 0-100 range) and [[quantile]].
(r2 [vs1 vs2-or-val])(r2 vs1 vs2-or-val)(r2 vs1 vs2-or-val no-of-variables)Calculates the Coefficient of Determination ($R^2$) or adjusted version between two sequences or a sequence and a constant value.
$R^2$ is a statistical measure that represents the proportion of the variance in the dependent variable that is predictable from the independent variable(s) in a statistical model. It indicates how well the model fits the observed data.
The standard $R^2$ is calculated as $1 - (RSS / TSS)$, where:
vs1) and the predicted/reference values (vs2 or vs2-or-val).
See rss.vs1) and their mean. This is calculated
using moment of order 2 with :mean? set to false.This function has two arities:
(r2 vs1 vs2-or-val): Calculates the standard $R^2$.
vs1 (seq of numbers): The sequence of observed or actual values.vs2-or-val (seq of numbers or single number): The sequence of predicted or
reference values, or a single constant value to compare against.Returns the calculated standard $R^2$ as a double. For simple linear regression,
this is equal to the square of the Pearson correlation coefficient (r2-determination).
$R^2$ typically ranges from 0 to 1 in this context, but can be negative
if the chosen model fits the data worse than a horizontal line through the mean
of the observed data.
(r2 vs1 vs2-or-val no-of-variables): Calculates the Adjusted $R^2$.
The adjusted $R^2$ is a modified version of $R^2$ that has been adjusted
for the number of predictors in the model. It increases only if the new term
improves the model more than would be expected by chance.
The formula for adjusted $R^2$ is:
$$ R^2_{adj} = 1 - (1 - R^2) \frac{n-1}{n-p-1} $$
where $n$ is the number of observations (length of vs1) and $p$ is the
number of independent variables (no-of-variables).
vs1 (seq of numbers): The sequence of observed or actual values.vs2-or-val (seq of numbers or single number): The sequence of predicted or
reference values, or a single constant value to compare against.no-of-variables (double): The number of independent variables ($p$) used in the model
that produced the vs2-or-val predictions.Returns the calculated adjusted $R^2$ as a double.
Both vs1 and vs2 (if vs2-or-val is a sequence) must have the same length.
See also rss, mse, rmse, pearson-correlation, r2-determination.
Calculates the Coefficient of Determination ($R^2$) or adjusted version between two sequences or a sequence and a constant value.
$R^2$ is a statistical measure that represents the proportion of the variance in the
dependent variable that is predictable from the independent variable(s) in a
statistical model. It indicates how well the model fits the observed data.
The standard $R^2$ is calculated as $1 - (RSS / TSS)$, where:
- $RSS$ (Residual Sum of Squares) is the sum of the squared differences
between the observed values (`vs1`) and the predicted/reference values (`vs2` or `vs2-or-val`).
See [[rss]].
- $TSS$ (Total Sum of Squares) is the sum of the squared differences
between the observed values (`vs1`) and their mean. This is calculated
using [[moment]] of order 2 with `:mean?` set to `false`.
This function has two arities:
1. `(r2 vs1 vs2-or-val)`: Calculates the standard $R^2$.
- `vs1` (seq of numbers): The sequence of observed or actual values.
- `vs2-or-val` (seq of numbers or single number): The sequence of predicted or
reference values, or a single constant value to compare against.
Returns the calculated standard $R^2$ as a double. For simple linear regression,
this is equal to the square of the Pearson correlation coefficient ([[r2-determination]]).
$R^2$ typically ranges from 0 to 1 in this context, but can be negative
if the chosen model fits the data worse than a horizontal line through the mean
of the observed data.
2. `(r2 vs1 vs2-or-val no-of-variables)`: Calculates the **Adjusted $R^2$**.
The adjusted $R^2$ is a modified version of $R^2$ that has been adjusted
for the number of predictors in the model. It increases only if the new term
improves the model more than would be expected by chance.
The formula for adjusted $R^2$ is:
$$ R^2_{adj} = 1 - (1 - R^2) \frac{n-1}{n-p-1} $$
where $n$ is the number of observations (length of `vs1`) and $p$ is the
number of independent variables (`no-of-variables`).
- `vs1` (seq of numbers): The sequence of observed or actual values.
- `vs2-or-val` (seq of numbers or single number): The sequence of predicted or
reference values, or a single constant value to compare against.
- `no-of-variables` (double): The number of independent variables ($p$) used in the model
that produced the `vs2-or-val` predictions.
Returns the calculated adjusted $R^2$ as a double.
Both `vs1` and `vs2` (if `vs2-or-val` is a sequence) must have the same length.
See also [[rss]], [[mse]], [[rmse]], [[pearson-correlation]], [[r2-determination]].(r2-determination [group1 group2])(r2-determination group1 group2)Calculates the Coefficient of Determination ($R^2$) between two sequences.
This function computes the square of the Pearson product-moment correlation
coefficient (pearson-correlation) between group1 and group2.
$R^2$ measures the proportion of the variance in one variable that is predictable from the other variable in a linear relationship. For a simple linear regression with one independent variable, this value is equivalent to the $R^2$ calculated from the Residual Sum of Squares (RSS) and Total Sum of Squares (TSS).
Parameters:
group1 (seq of numbers): The first sequence.group2 (seq of numbers): The second sequence.Both sequences must have the same length.
Returns the calculated $R^2$ value (a double between 0.0 and 1.0) as a double.
Returns NaN if the Pearson correlation cannot be calculated (e.g., one sequence is constant).
See also r2 (for general $R^2$ and adjusted $R^2$), pearson-correlation.
Calculates the Coefficient of Determination ($R^2$) between two sequences. This function computes the square of the Pearson product-moment correlation coefficient ([[pearson-correlation]]) between `group1` and `group2`. $R^2$ measures the proportion of the variance in one variable that is predictable from the other variable in a linear relationship. For a simple linear regression with one independent variable, this value is equivalent to the $R^2$ calculated from the Residual Sum of Squares (RSS) and Total Sum of Squares (TSS). Parameters: - `group1` (seq of numbers): The first sequence. - `group2` (seq of numbers): The second sequence. Both sequences must have the same length. Returns the calculated $R^2$ value (a double between 0.0 and 1.0) as a double. Returns `NaN` if the Pearson correlation cannot be calculated (e.g., one sequence is constant). See also [[r2]] (for general $R^2$ and adjusted $R^2$), [[pearson-correlation]].
(rank-epsilon-sq xss)Calculates Rank Epsilon-squared (ε²), a measure of effect size for the Kruskal-Wallis H-test.
Rank Epsilon-squared is a non-parametric measure quantifying the proportion of the total variability (based on ranks) in the dependent variable that is associated with group membership (the independent variable). It is analogous to Eta-squared or Epsilon-squared in one-way ANOVA but used for the rank-based Kruskal-Wallis test.
This function calculates Epsilon-squared based on the Kruskal-Wallis H statistic (H)
and the total number of observations (n) across all groups.
Parameters:
xss (sequence of sequences): A collection where each element is a sequence
representing a group of observations, as used in kruskal-test.Returns the calculated Rank Epsilon-squared value as a double, ranging from 0 to 1.
Interpretation:
Rank Epsilon-squared is a useful supplement to the Kruskal-Wallis test, providing a measure of the magnitude of the group effect that is not sensitive to assumptions about the data distribution shape (beyond having similar shapes for valid interpretation of the Kruskal-Wallis test itself).
See also kruskal-test, rank-eta-sq (another rank-based effect size).
Calculates Rank Epsilon-squared (ε²), a measure of effect size for the Kruskal-Wallis H-test. Rank Epsilon-squared is a non-parametric measure quantifying the proportion of the total variability (based on ranks) in the dependent variable that is associated with group membership (the independent variable). It is analogous to Eta-squared or Epsilon-squared in one-way ANOVA but used for the rank-based Kruskal-Wallis test. This function calculates Epsilon-squared based on the Kruskal-Wallis H statistic (`H`) and the total number of observations (`n`) across all groups. Parameters: - `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in [[kruskal-test]]. Returns the calculated Rank Epsilon-squared value as a double, ranging from 0 to 1. Interpretation: - A value of 0 indicates no difference in the distributions across groups. - A value closer to 1 indicates that a large proportion of the variability is due to differences between group ranks. Rank Epsilon-squared is a useful supplement to the Kruskal-Wallis test, providing a measure of the magnitude of the group effect that is not sensitive to assumptions about the data distribution shape (beyond having similar shapes for valid interpretation of the Kruskal-Wallis test itself). See also [[kruskal-test]], [[rank-eta-sq]] (another rank-based effect size).
(rank-eta-sq xss)Calculates the Rank Eta-squared (η²), an effect size measure for the Kruskal-Wallis H-test.
Rank Eta-squared is a non-parametric measure quantifying the proportion of the total variability (based on ranks) in the dependent variable that is associated with group membership (the independent variable). It is analogous to Eta-squared in one-way ANOVA but used for the rank-based Kruskal-Wallis test.
The statistic is calculated based on the Kruskal-Wallis H statistic, the number
of groups (k), and the total number of observations (n).
Parameters:
xss (sequence of sequences): A collection where each element is a sequence
representing a group of observations, as used in kruskal-test.Returns the calculated Rank Eta-squared value as a double, ranging from 0 to 1.
Interpretation:
Rank Eta-squared is a useful supplement to the Kruskal-Wallis test, providing a measure of the magnitude of the group effect that is not sensitive to assumptions about the data distribution shape (beyond having similar shapes for valid interpretation of the Kruskal-Wallis test itself).
See also kruskal-test, rank-epsilon-sq (another rank-based effect size).
Calculates the Rank Eta-squared (η²), an effect size measure for the Kruskal-Wallis H-test. Rank Eta-squared is a non-parametric measure quantifying the proportion of the total variability (based on ranks) in the dependent variable that is associated with group membership (the independent variable). It is analogous to Eta-squared in one-way ANOVA but used for the rank-based Kruskal-Wallis test. The statistic is calculated based on the Kruskal-Wallis H statistic, the number of groups (`k`), and the total number of observations (`n`). Parameters: - `xss` (sequence of sequences): A collection where each element is a sequence representing a group of observations, as used in [[kruskal-test]]. Returns the calculated Rank Eta-squared value as a double, ranging from 0 to 1. Interpretation: - A value of 0 indicates no difference in the distributions across groups (all variability is within groups). - A value closer to 1 indicates that a large proportion of the variability is due to differences between group ranks. Rank Eta-squared is a useful supplement to the Kruskal-Wallis test, providing a measure of the magnitude of the group effect that is not sensitive to assumptions about the data distribution shape (beyond having similar shapes for valid interpretation of the Kruskal-Wallis test itself). See also [[kruskal-test]], [[rank-epsilon-sq]] (another rank-based effect size).
(remove-outliers vs)(remove-outliers vs estimation-strategy)(remove-outliers vs q1 q3)Removes outliers from vs, defined as values falling outside the inner fences.
Let Q1 and Q3 be the 25th and 75th percentiles and IQR = Q3 - Q1. A value is considered an outlier when it is below the lower inner fence, Q1 - 1.5*IQR, or above the upper inner fence, Q3 + 1.5*IQR.
Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Percentile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.q1, q3 (doubles): Precomputed first and third quartiles, used instead of computing them from vs.Returns a lazy sequence of the values from vs that lie within the inner fences, in their original order.
See also outliers, inner-fence-extent, adjacent-values, iqr.
Removes outliers from `vs`, defined as values falling outside the inner fences. Let `Q1` and `Q3` be the 25th and 75th percentiles and `IQR = Q3 - Q1`. A value is considered an outlier when it is below the lower inner fence, `Q1 - 1.5*IQR`, or above the upper inner fence, `Q3 + 1.5*IQR`. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Percentile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. - `q1`, `q3` (doubles): Precomputed first and third quartiles, used instead of computing them from `vs`. Returns a lazy sequence of the values from `vs` that lie within the inner fences, in their original order. See also [[outliers]], [[inner-fence-extent]], [[adjacent-values]], [[iqr]].
(rescale vs)(rescale vs low high)Linearly rescales vs from its observed range to a target range, [0,1] by default.
Each value is mapped from [min(vs), max(vs)] to [low, high] using linear interpolation, see fastmath.core/make-norm.
Parameters:
vs (sequence of numbers): Input data.low, high (doubles): Target range bounds. Default to 0.0 and 1.0.Returns a lazy sequence of the same length as vs, rescaled to [low, high].
Values are not clamped beyond [low, high], since min(vs) and max(vs) always map exactly to low and high. Constant input (min(vs) = max(vs)) leads to division by zero.
See also standardize, demean, extent.
Linearly rescales `vs` from its observed range to a target range, `[0,1]` by default. Each value is mapped from `[min(vs), max(vs)]` to `[low, high]` using linear interpolation, see [[fastmath.core/make-norm]]. Parameters: - `vs` (sequence of numbers): Input data. - `low`, `high` (doubles): Target range bounds. Default to `0.0` and `1.0`. Returns a lazy sequence of the same length as `vs`, rescaled to `[low, high]`. Values are not clamped beyond `[low, high]`, since `min(vs)` and `max(vs)` always map exactly to `low` and `high`. Constant input (`min(vs) = max(vs)`) leads to division by zero. See also [[standardize]], [[demean]], [[extent]].
(rmse [vs1 vs2-or-val])(rmse vs1 vs2-or-val)(rmse vs1 vs2-or-val weights)Calculates the Root Mean Squared Error (RMSE) between two sequences or a sequence and a constant value.
RMSE is the square root of the mse (Mean Squared Error). It represents the
standard deviation of the residuals (prediction errors) and has the same units
as the original data, making it more interpretable than MSE. It measures the
average magnitude of the errors, penalizing larger errors more than smaller ones
due to the squaring involved.
Parameters:
vs1 (sequence of numbers): The first sequence (often the observed or true values).vs2-or-val (sequence of numbers or single number): The second sequence
(often the predicted or reference values), or a single number to compare
against each element of vs1.If both inputs are sequences, they must have the same length. If vs2-or-val
is a single number, it is effectively treated as a sequence of that number
repeated count(vs1) times.
Returns the calculated Root Mean Squared Error as a double.
See also mse (Mean Squared Error), rss (Residual Sum of Squares),
me (Mean Error), mae (Mean Absolute Error), r2 (Coefficient of Determination).
Calculates the Root Mean Squared Error (RMSE) between two sequences or a sequence and a constant value. RMSE is the square root of the [[mse]] (Mean Squared Error). It represents the standard deviation of the residuals (prediction errors) and has the same units as the original data, making it more interpretable than MSE. It measures the average magnitude of the errors, penalizing larger errors more than smaller ones due to the squaring involved. Parameters: - `vs1` (sequence of numbers): The first sequence (often the observed or true values). - `vs2-or-val` (sequence of numbers or single number): The second sequence (often the predicted or reference values), or a single number to compare against each element of `vs1`. If both inputs are sequences, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated Root Mean Squared Error as a double. See also [[mse]] (Mean Squared Error), [[rss]] (Residual Sum of Squares), [[me]] (Mean Error), [[mae]] (Mean Absolute Error), [[r2]] (Coefficient of Determination).
(robust-standardize vs)(robust-standardize vs q)Standardizes vs using robust, outlier-resistant statistics instead of mean and standard deviation.
Each value x in vs is transformed to (x - median) / scale. By default scale is the median absolute deviation (MAD, see median-absolute-deviation), giving a result centered at 0 with MAD = 1. This is a robust counterpart of standardize, less sensitive to outliers.
Parameters:
vs (sequence of numbers): Input data.q (double, optional): When provided, scale is instead the quantile difference Q(1-q) - Q(q), in range (0,0.5). For example, 0.25 uses the interquartile range (IQR) as the scale.Returns a lazy sequence of standardized values, of the same length as vs.
See also standardize, median, median-absolute-deviation, iqr, quantiles.
Standardizes `vs` using robust, outlier-resistant statistics instead of mean and standard deviation. Each value `x` in `vs` is transformed to `(x - median) / scale`. By default `scale` is the median absolute deviation (MAD, see [[median-absolute-deviation]]), giving a result centered at `0` with `MAD = 1`. This is a robust counterpart of [[standardize]], less sensitive to outliers. Parameters: - `vs` (sequence of numbers): Input data. - `q` (double, optional): When provided, `scale` is instead the quantile difference `Q(1-q) - Q(q)`, in range `(0,0.5)`. For example, `0.25` uses the interquartile range (IQR) as the scale. Returns a lazy sequence of standardized values, of the same length as `vs`. See also [[standardize]], [[median]], [[median-absolute-deviation]], [[iqr]], [[quantiles]].
(robust-stddev vs)(robust-stddev vs typ)Estimates the standard deviation of vs with a (more or less) outlier resistant scale estimator.
Every method measures the spread of the data in its own way and multiplies it by a constant, so that the result estimates sigma for a large sample from the normal distribution N(mu, sigma). For other distributions the methods give different values.
Parameters:
vs (sequence of numbers): Input data. It should not contain NaN.typ (keyword or number): Estimation method, defaults to :mad. One of:
:mad: median absolute deviation from the median, see median-absolute-deviation, divided by 0.6744897501960816 (the 75th percentile of the standard normal distribution). Equals R mad(x, constant=1/qnorm(0.75)).:iqr: interquartile range, see iqr (quantiles of the :legacy estimation strategy, R type=6), divided by 1.3489795003921632.:sn: Rousseeuw-Croux Sn, 1.1926 c_n med_i med_j |xi - xj|, with medians of all n values including j = i. c_n is the finite sample correction of robustbase: 0.743 1.851 0.954 1.351 0.993 1.198 1.005 1.131 for n = 2..9, n / (n - 0.9) for odd n > 9 and 1 for even n > 9. Needs O(n^2) time. Equals R robustbase::Sn(x, constant=1.1926, finite.corr=TRUE) for odd n. For even n the medians are averages of the two middle values, while robustbase takes the low median of the high medians, so the results differ (for n = 2 by the factor of 2).:qn: Rousseeuw-Croux Qn, 2.21914 times the k-th smallest distance |xi - xj|, i < j, k = h (h - 1) / 2, h = floor(n / 2) + 1, without the finite sample correction. Equals R robustbase::Qn(x, constant=2.21914, finite.corr=FALSE). Needs O(n^2) time and memory (n (n - 1) / 2 distances), use it for samples up to a few thousands values.:tukey (or :biweight): square root of Tukey's biweight midvariance, centered at the median, with the tuning constant 9 times the (not normalized) MAD. Equals astropy.stats.biweight_scale(x, c=9). Returns 0.0 when the MAD is zero.:stddev: the sample standard deviation, see stddev. Not robust.:meanad: mean absolute deviation from the mean, see mean-absolute-deviation, multiplied by sqrt(pi/2). Not robust.:gini: Gini's mean difference, the mean of |xi - xj| over all pairs i < j, multiplied by sqrt(pi)/2. Equals R Hmisc::GiniMd(x) * sqrt(pi) / 2. Less sensitive to outliers than :stddev, not robust.p from (0, 0.5): the spread between the quantiles p and 1-p (the :legacy strategy) divided by 2 z, where z is the 1-p quantile of the standard normal distribution. 0.25 is :iqr. The values p and 1-p give the same result.Returns the estimate as a double.
Corner cases:
vs gives NaN and a single value gives 0.0, for every method; a constant sequence gives 0.0; :mad and :tukey also give 0.0 when more than half of the values are equalp = 0.5 gives NaN, p = 0 or p = 1 gives 0.0, p outside of [0,1] throws OutOfRangeExceptiontyp throws IllegalArgumentException (not checked for an empty vs and a single value)See also median-absolute-deviation, mean-absolute-deviation, iqr, stddev, robust-standardize.
Estimates the standard deviation of `vs` with a (more or less) outlier resistant scale estimator. Every method measures the spread of the data in its own way and multiplies it by a constant, so that the result estimates `sigma` for a large sample from the normal distribution `N(mu, sigma)`. For other distributions the methods give different values. Parameters: - `vs` (sequence of numbers): Input data. It should not contain `NaN`. - `typ` (keyword or number): Estimation method, defaults to `:mad`. One of: - `:mad`: median absolute deviation from the median, see [[median-absolute-deviation]], divided by `0.6744897501960816` (the 75th percentile of the standard normal distribution). Equals R `mad(x, constant=1/qnorm(0.75))`. - `:iqr`: interquartile range, see [[iqr]] (quantiles of the `:legacy` estimation strategy, R `type=6`), divided by `1.3489795003921632`. - `:sn`: Rousseeuw-Croux `Sn`, `1.1926 c_n med_i med_j |xi - xj|`, with medians of all `n` values including `j = i`. `c_n` is the finite sample correction of `robustbase`: `0.743 1.851 0.954 1.351 0.993 1.198 1.005 1.131` for `n = 2..9`, `n / (n - 0.9)` for odd `n > 9` and `1` for even `n > 9`. Needs `O(n^2)` time. Equals R `robustbase::Sn(x, constant=1.1926, finite.corr=TRUE)` for odd `n`. For even `n` the medians are averages of the two middle values, while `robustbase` takes the low median of the high medians, so the results differ (for `n = 2` by the factor of 2). - `:qn`: Rousseeuw-Croux `Qn`, `2.21914` times the `k`-th smallest distance `|xi - xj|`, `i < j`, `k = h (h - 1) / 2`, `h = floor(n / 2) + 1`, without the finite sample correction. Equals R `robustbase::Qn(x, constant=2.21914, finite.corr=FALSE)`. Needs `O(n^2)` time and memory (`n (n - 1) / 2` distances), use it for samples up to a few thousands values. - `:tukey` (or `:biweight`): square root of Tukey's biweight midvariance, centered at the median, with the tuning constant `9` times the (not normalized) MAD. Equals `astropy.stats.biweight_scale(x, c=9)`. Returns `0.0` when the MAD is zero. - `:stddev`: the sample standard deviation, see [[stddev]]. Not robust. - `:meanad`: mean absolute deviation from the mean, see [[mean-absolute-deviation]], multiplied by `sqrt(pi/2)`. Not robust. - `:gini`: Gini's mean difference, the mean of `|xi - xj|` over all pairs `i < j`, multiplied by `sqrt(pi)/2`. Equals R `Hmisc::GiniMd(x) * sqrt(pi) / 2`. Less sensitive to outliers than `:stddev`, not robust. - a number `p` from `(0, 0.5)`: the spread between the quantiles `p` and `1-p` (the `:legacy` strategy) divided by `2 z`, where `z` is the `1-p` quantile of the standard normal distribution. `0.25` is `:iqr`. The values `p` and `1-p` give the same result. Returns the estimate as a double. Corner cases: - an empty `vs` gives `NaN` and a single value gives `0.0`, for every method; a constant sequence gives `0.0`; `:mad` and `:tukey` also give `0.0` when more than half of the values are equal - `p = 0.5` gives `NaN`, `p = 0` or `p = 1` gives `0.0`, `p` outside of `[0,1]` throws `OutOfRangeException` - an unknown `typ` throws `IllegalArgumentException` (not checked for an empty `vs` and a single value) See also [[median-absolute-deviation]], [[mean-absolute-deviation]], [[iqr]], [[stddev]], [[robust-standardize]].
(rows->contingency-table xss)Converts a sequence of sequences (representing rows of counts) into a map-based contingency table.
This function takes a collection where each inner sequence is treated as a row
of counts in a grid or matrix. It transforms this matrix representation into a
map where keys are [row-index, column-index] tuples and values are the
non-zero counts at that intersection.
This is particularly useful for converting structured count data, like the
output of some grouping or tabulation processes, into a format suitable for
functions expecting a contingency table map (like contingency-table->marginals
or chi-squared tests).
Parameters:
xss (sequence of sequences of numbers): A collection where each inner
sequence xs_i contains counts for row i. Values within xs_i are
interpreted as counts for columns 0, 1, ....Returns a map where keys are [row-index, column-index] vectors and values
are the corresponding non-zero counts from the input matrix. Zero counts are
omitted from the output map.
See also contingency-table (for building tables from raw data), contingency-table->marginals.
Converts a sequence of sequences (representing rows of counts) into a map-based contingency table. This function takes a collection where each inner sequence is treated as a row of counts in a grid or matrix. It transforms this matrix representation into a map where keys are `[row-index, column-index]` tuples and values are the non-zero counts at that intersection. This is particularly useful for converting structured count data, like the output of some grouping or tabulation processes, into a format suitable for functions expecting a contingency table map (like `contingency-table->marginals` or chi-squared tests). Parameters: - `xss` (sequence of sequences of numbers): A collection where each inner sequence `xs_i` contains counts for row `i`. Values within `xs_i` are interpreted as counts for columns `0, 1, ...`. Returns a map where keys are `[row-index, column-index]` vectors and values are the corresponding non-zero counts from the input matrix. Zero counts are omitted from the output map. See also [[contingency-table]] (for building tables from raw data), [[contingency-table->marginals]].
(rss [vs1 vs2-or-val])(rss vs1 vs2-or-val)Calculates the Residual Sum of Squares (RSS) between two sequences or a sequence and a constant value.
RSS is a measure of the discrepancy between data and a model, often used in regression analysis to quantify the total squared difference between observed values and predicted (or reference) values.
Parameters:
vs1 (sequence of numbers): The first sequence (often observed values).vs2-or-val (sequence of numbers or single number): The second sequence
(often predicted or reference values), or a single number to compare
against each element of vs1.If both sequences (vs1 and vs2) are provided, they must have the same length.
If vs2-or-val is a single number, it is effectively treated as a sequence
of that number repeated count(vs1) times.
Returns the calculated Residual Sum of Squares as a double.
See also mse (Mean Squared Error), rmse (Root Mean Squared Error), r2 (Coefficient of Determination).
Calculates the Residual Sum of Squares (RSS) between two sequences or a sequence and a constant value. RSS is a measure of the discrepancy between data and a model, often used in regression analysis to quantify the total squared difference between observed values and predicted (or reference) values. Parameters: - `vs1` (sequence of numbers): The first sequence (often observed values). - `vs2-or-val` (sequence of numbers or single number): The second sequence (often predicted or reference values), or a single number to compare against each element of `vs1`. If both sequences (`vs1` and `vs2`) are provided, they must have the same length. If `vs2-or-val` is a single number, it is effectively treated as a sequence of that number repeated `count(vs1)` times. Returns the calculated Residual Sum of Squares as a double. See also [[mse]] (Mean Squared Error), [[rmse]] (Root Mean Squared Error), [[r2]] (Coefficient of Determination).
(sem vs)Calculates the Standard Error of the Mean (SEM) for a sequence vs.
The SEM estimates the standard deviation of the sample mean, providing an indication of how accurately the sample mean represents the population mean. It is calculated as:
SEM = stddev(vs) / sqrt(count(vs))
where stddev(vs) is the sample standard deviation and count(vs) is the
sample size.
Parameters:
vs: Sequence of numbers.Returns the calculated SEM as a double.
A smaller SEM indicates that the sample mean is likely to be a more precise estimate of the population mean.
Calculates the Standard Error of the Mean (SEM) for a sequence `vs`. The SEM estimates the standard deviation of the sample mean, providing an indication of how accurately the sample mean represents the population mean. It is calculated as: `SEM = stddev(vs) / sqrt(count(vs))` where `stddev(vs)` is the sample standard deviation and `count(vs)` is the sample size. Parameters: - `vs`: Sequence of numbers. Returns the calculated SEM as a double. A smaller SEM indicates that the sample mean is likely to be a more precise estimate of the population mean. See also [[stddev]], [[mean]].
(sem-extent vs)Calculates the mean of vs together with its -/+ standard error of the mean (SEM) extent.
Parameters:
vs (sequence of numbers): Input data.Returns a 3-element vector [(m/- mean sem), (m/+ mean sem), mean].
See also mean, sem, stddev-extent, mad-extent.
Calculates the mean of `vs` together with its `-/+` standard error of the mean (SEM) extent. Parameters: - `vs` (sequence of numbers): Input data. Returns a 3-element vector `[(m/- mean sem), (m/+ mean sem), mean]`. See also [[mean]], [[sem]], [[stddev-extent]], [[mad-extent]].
(similarity method P-observed Q-expected)(similarity method
P-observed
Q-expected
{:keys [bins probabilities? epsilon]
:or {probabilities? true epsilon 1.0E-6}})Calculates a similarity measure between two probability density functions, P-observed and Q-expected, given as histograms, frequencies, probabilities, or raw data.
If Q-expected is a distribution object, a histogram is built from P-observed and compared against it directly. If :bins is set (and Q-expected is not a distribution), both P-observed and Q-expected are treated as raw data and turned into a matching pair of histograms.
Parameters:
method (keyword): Similarity method to use, see below.P-observed (sequence of numbers): Frequencies, probabilities, or raw data.Q-expected (sequence of numbers, or distribution object): Frequencies, probabilities, raw data, or a distribution object to compare P-observed against.opts (map, optional):
:probabilities? (boolean): Whether P-observed/Q-expected are normalized to probabilities (summing to 1) before computing the similarity. Defaults to true.:bins (long or keyword): Number of bins, or a bin-count estimation method, used to turn raw P-observed/Q-expected data into histograms, see histogram and estimate-bins.:epsilon (double): Small number substituted for 0.0 wherever a division would otherwise be undefined. Defaults to 1.0e-6.method is one of: :intersection, :czekanowski, :motyka, :kulczynski, :ruzicka, :inner-product, :harmonic-mean, :cosine, :jaccard, :dice, :fidelity, :squared-chord.
Returns the calculated similarity as a double. Higher values generally indicate more similar distributions, though the range and interpretation depend on the chosen method.
Definitions for the individual methods are given in the Comprehensive Survey on Distance/Similarity Measures between Probability Density Functions by Sung-Hyuk Cha.
See also dissimilarity, histogram, estimate-bins.
Calculates a similarity measure between two probability density functions, `P-observed` and `Q-expected`, given as histograms, frequencies, probabilities, or raw data. If `Q-expected` is a distribution object, a histogram is built from `P-observed` and compared against it directly. If `:bins` is set (and `Q-expected` is not a distribution), both `P-observed` and `Q-expected` are treated as raw data and turned into a matching pair of histograms. Parameters: - `method` (keyword): Similarity method to use, see below. - `P-observed` (sequence of numbers): Frequencies, probabilities, or raw data. - `Q-expected` (sequence of numbers, or distribution object): Frequencies, probabilities, raw data, or a distribution object to compare `P-observed` against. - `opts` (map, optional): - `:probabilities?` (boolean): Whether `P-observed`/`Q-expected` are normalized to probabilities (summing to `1`) before computing the similarity. Defaults to `true`. - `:bins` (long or keyword): Number of bins, or a bin-count estimation method, used to turn raw `P-observed`/`Q-expected` data into histograms, see [[histogram]] and [[estimate-bins]]. - `:epsilon` (double): Small number substituted for `0.0` wherever a division would otherwise be undefined. Defaults to `1.0e-6`. `method` is one of: `:intersection`, `:czekanowski`, `:motyka`, `:kulczynski`, `:ruzicka`, `:inner-product`, `:harmonic-mean`, `:cosine`, `:jaccard`, `:dice`, `:fidelity`, `:squared-chord`. Returns the calculated similarity as a double. Higher values generally indicate more similar distributions, though the range and interpretation depend on the chosen `method`. Definitions for the individual methods are given in the Comprehensive Survey on Distance/Similarity Measures between Probability Density Functions by Sung-Hyuk Cha. See also [[dissimilarity]], [[histogram]], [[estimate-bins]].
(skewness vs)(skewness vs typ)Calculates the skewness of vs, a measure of the asymmetry of a probability distribution about its mean.
Several skewness definitions are supported through the typ argument, ranging from moment-based estimators to robust, quantile- or trimmed-mean-based estimators.
Parameters:
vs (sequence of numbers): Input data.typ (keyword or sequence): Skewness measure to calculate. Defaults to :G1. One of:
:G1 (default): sample skewness based on the third standardized moment, adjusted for sample size bias, as implemented by Apache Commons Math Skewness.:g1 or :pearson: Pearson's moment coefficient of skewness, a bias-adjusted version of the third standardized moment. Expected value 0 for symmetric distributions.:b1: sample skewness coefficient (b1), related to :g1.:B1 or :yule: Yule's coefficient (robust), based on quantiles. The sequence form [:B1 u] or [:yule u] sets the quantile u used, default 0.25.:B3: robust measure comparing the mean and median relative to the mean absolute deviation around the median.:skew: an adjusted skewness definition sometimes used in bootstrap (BCa) calculations.:mode: Pearson's second skewness coefficient, (mean - mode) / stddev. The sequence form [:mode method opts] sets the mode estimation method and its opts, see mode.:median: robust measure, 3 * (mean - median) / stddev.:bowley: Bowley's coefficient (robust), also known as the Yule-Bowley coefficient, based on quartiles Q1, Q2, Q3: (Q3 + Q1 - 2*Q2) / (Q3 - Q1).:hogg: Hogg's robust measure, based on the ratio of differences between trimmed means.:l-skewness: L-skewness (τ₃), the ratio of the third L-moment (λ₃) to the second L-moment (λ₂, L-scale), a robust measure of asymmetry. Calculated directly using l-moment with :ratio? set to true. Expected value 0 for symmetric distributions.Positive values generally indicate a distribution skewed to the right (a longer tail on the right), negative values indicate a distribution skewed to the left (a longer tail on the left), and values near 0 suggest relative symmetry.
Returns the calculated skewness as a double.
See also skewness-test, kurtosis, normality-test, jarque-bera-test, l-moment, moment.
Calculates the skewness of `vs`, a measure of the asymmetry of a probability distribution about its mean. Several skewness definitions are supported through the `typ` argument, ranging from moment-based estimators to robust, quantile- or trimmed-mean-based estimators. Parameters: - `vs` (sequence of numbers): Input data. - `typ` (keyword or sequence): Skewness measure to calculate. Defaults to `:G1`. One of: - `:G1` (default): sample skewness based on the third standardized moment, adjusted for sample size bias, as implemented by Apache Commons Math `Skewness`. - `:g1` or `:pearson`: Pearson's moment coefficient of skewness, a bias-adjusted version of the third standardized moment. Expected value `0` for symmetric distributions. - `:b1`: sample skewness coefficient (b1), related to `:g1`. - `:B1` or `:yule`: Yule's coefficient (robust), based on quantiles. The sequence form `[:B1 u]` or `[:yule u]` sets the quantile `u` used, default `0.25`. - `:B3`: robust measure comparing the mean and median relative to the mean absolute deviation around the median. - `:skew`: an adjusted skewness definition sometimes used in bootstrap (BCa) calculations. - `:mode`: Pearson's second skewness coefficient, `(mean - mode) / stddev`. The sequence form `[:mode method opts]` sets the mode estimation `method` and its `opts`, see [[mode]]. - `:median`: robust measure, `3 * (mean - median) / stddev`. - `:bowley`: Bowley's coefficient (robust), also known as the Yule-Bowley coefficient, based on quartiles `Q1`, `Q2`, `Q3`: `(Q3 + Q1 - 2*Q2) / (Q3 - Q1)`. - `:hogg`: Hogg's robust measure, based on the ratio of differences between trimmed means. - `:l-skewness`: L-skewness (τ₃), the ratio of the third L-moment (λ₃) to the second L-moment (λ₂, L-scale), a robust measure of asymmetry. Calculated directly using [[l-moment]] with `:ratio?` set to `true`. Expected value `0` for symmetric distributions. Positive values generally indicate a distribution skewed to the right (a longer tail on the right), negative values indicate a distribution skewed to the left (a longer tail on the left), and values near `0` suggest relative symmetry. Returns the calculated skewness as a double. See also [[skewness-test]], [[kurtosis]], [[normality-test]], [[jarque-bera-test]], [[l-moment]], [[moment]].
(skewness-test xs)(skewness-test xs params)(skewness-test xs skew {:keys [sides type] :or {sides :two-sided type :g1}})Performs the D'Agostino test for normality based on sample skewness.
This test assesses the null hypothesis that the data comes from a normally distributed population by checking if the sample skewness significantly deviates from the zero skewness expected under normality.
The test works by:
:type, default :g1).Z that more closely
follows a standard normal distribution under the null hypothesis.Parameters:
xs (seq of numbers): The sample data.skew (double, optional): A pre-calculated skewness value. If omitted, it's calculated from xs.params (map, optional): Options map:
:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): The population skewness is different from 0.:one-sided-greater: The population skewness is greater than 0 (right-skewed).:one-sided-less: The population skewness is less than 0 (left-skewed).:type (keyword, default :g1): The type of skewness to calculate if skew is not provided. Note that the internal normalization constants are derived based on :g1. See skewness for options.Returns a map containing:
:Z: The final test statistic, approximately standard normal under H0.:stat: Alias for :Z.:p-value: The p-value associated with Z and the specified :sides.:skewness: The sample skewness value used in the test (either provided or calculated).See also kurtosis-test, normality-test, jarque-bera-test.
Performs the D'Agostino test for normality based on sample skewness.
This test assesses the null hypothesis that the data comes from a normally
distributed population by checking if the sample skewness significantly deviates
from the zero skewness expected under normality.
The test works by:
1. Calculating the sample skewness (type configurable via `:type`, default `:g1`).
2. Standardizing the sample skewness relative to its expected value (0) and
standard error under the null hypothesis.
3. Applying a further transformation (inverse hyperbolic sine based) to this
standardized score to yield a final test statistic `Z` that more closely
follows a standard normal distribution under the null hypothesis.
Parameters:
- `xs` (seq of numbers): The sample data.
- `skew` (double, optional): A pre-calculated skewness value. If omitted, it's calculated from `xs`.
- `params` (map, optional): Options map:
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): The population skewness is different from 0.
- `:one-sided-greater`: The population skewness is greater than 0 (right-skewed).
- `:one-sided-less`: The population skewness is less than 0 (left-skewed).
- `:type` (keyword, default `:g1`): The type of skewness to calculate if `skew` is not provided. Note that the internal normalization constants are derived based on `:g1`. See [[skewness]] for options.
Returns a map containing:
- `:Z`: The final test statistic, approximately standard normal under H0.
- `:stat`: Alias for `:Z`.
- `:p-value`: The p-value associated with `Z` and the specified `:sides`.
- `:skewness`: The sample skewness value used in the test (either provided or calculated).
See also [[kurtosis-test]], [[normality-test]], [[jarque-bera-test]].(span vs)Calculates the span (range width) of vs.
The span is the difference between the maximum and the minimum values of the data, and gives the total width covered by the sample.
Parameters:
vs (sequence of numbers): Input data.Returns the span as a double. Returns 0.0 when all values in vs are equal.
Calculates the span (range width) of `vs`. The span is the difference between the maximum and the minimum values of the data, and gives the total width covered by the sample. Parameters: - `vs` (sequence of numbers): Input data. Returns the span as a double. Returns `0.0` when all values in `vs` are equal. See also [[extent]], [[maximum]], [[minimum]].
(spearman-correlation [vs1 vs2])(spearman-correlation vs1 vs2)Calculates Spearman's rank correlation coefficient between two sequences.
Spearman's rank correlation is a non-parametric measure of the monotonic relationship between two datasets. It assesses how well the relationship between two variables can be described using a monotonic function. It does not require the data to be linearly related or follow a specific distribution. The coefficient is calculated on the ranks of the data rather than the raw values.
Parameters:
[vs1 vs2] (sequence of two sequences): A sequence containing the two sequences of numbers.vs1, vs2 (sequences): The two sequences of numbers directly as arguments.Both sequences must have the same length.
Returns the calculated Spearman rank correlation coefficient (a value between -1.0 and 1.0) as a double. A value of 1 indicates a perfect monotonic increasing relationship, -1 a perfect monotonic decreasing relationship, and 0 no monotonic relationship.
See also pearson-correlation, kendall-correlation, correlation.
Calculates Spearman's rank correlation coefficient between two sequences. Spearman's rank correlation is a non-parametric measure of the monotonic relationship between two datasets. It assesses how well the relationship between two variables can be described using a monotonic function. It does not require the data to be linearly related or follow a specific distribution. The coefficient is calculated on the ranks of the data rather than the raw values. Parameters: - `[vs1 vs2]` (sequence of two sequences): A sequence containing the two sequences of numbers. - `vs1`, `vs2` (sequences): The two sequences of numbers directly as arguments. Both sequences must have the same length. Returns the calculated Spearman rank correlation coefficient (a value between -1.0 and 1.0) as a double. A value of 1 indicates a perfect monotonic increasing relationship, -1 a perfect monotonic decreasing relationship, and 0 no monotonic relationship. See also [[pearson-correlation]], [[kendall-correlation]], [[correlation]].
(standardize vs)Standardizes vs (z-scores) so that the result has a mean of 0 and a standard deviation of 1.
Each value x in vs is transformed to (x - mean) / stddev, using the sample mean and sample standard deviation of vs.
Parameters:
vs (sequence of numbers): Input data.Returns a lazy sequence of standardized values, of the same length as vs.
Not robust to outliers; use robust-standardize for a median/MAD-based alternative.
See also robust-standardize, mean, stddev.
Standardizes `vs` (z-scores) so that the result has a mean of `0` and a standard deviation of `1`. Each value `x` in `vs` is transformed to `(x - mean) / stddev`, using the sample mean and sample standard deviation of `vs`. Parameters: - `vs` (sequence of numbers): Input data. Returns a lazy sequence of standardized values, of the same length as `vs`. Not robust to outliers; use [[robust-standardize]] for a median/MAD-based alternative. See also [[robust-standardize]], [[mean]], [[stddev]].
(stats-map vs)(stats-map vs estimation-strategy)Calculates a comprehensive set of descriptive statistics for vs and returns them as a map, giving a quick overview of the data's central tendency, dispersion, shape, and potential outliers.
Parameters:
vs (sequence of numbers): Input data.estimation-strategy (keyword): Quantile estimation method used for the median, quartiles, and fence-related statistics, one of the keys of estimation-strategies-list. Defaults to :legacy.Returns a map with the following keys:
:Size: number of data points, count.:Min: minimum value, see minimum.:Max: maximum value, see maximum.:Range: Max - Min.:Mean: arithmetic average, see mean.:Median: middle value, see median.:Mode: most frequent value, see mode (default method).:Q1: first quartile (25th percentile), see percentile.:Q3: third quartile (75th percentile), see percentile.:Total: sum of all values, see sum.:SD: sample standard deviation, see stddev.:Variance: sample variance, SD^2, see variance.:MAD: median absolute deviation, see median-absolute-deviation.:SEM: standard error of the mean, see sem.:LAV: lower adjacent value, the smallest value within the lower inner fence, see adjacent-values.:UAV: upper adjacent value, the largest value within the upper inner fence, see adjacent-values.:IQR: interquartile range, Q3 - Q1.:LOF: lower outer fence, Q1 - 3*IQR, see outer-fence-extent.:UOF: upper outer fence, Q3 + 3*IQR, see outer-fence-extent.:LIF: lower inner fence, Q1 - 1.5*IQR, see inner-fence-extent.:UIF: upper inner fence, Q3 + 1.5*IQR, see inner-fence-extent.:Outliers: sequence of data points falling outside the inner fences, see outliers.:Kurtosis: measure of tailedness/peakedness, see kurtosis (default :G2 type).:Skewness: measure of asymmetry, see skewness (default :G1 type).See also extent, percentile-extent, adjacent-values, inner-fence-extent, outer-fence-extent, outliers.
Calculates a comprehensive set of descriptive statistics for `vs` and returns them as a map, giving a quick overview of the data's central tendency, dispersion, shape, and potential outliers. Parameters: - `vs` (sequence of numbers): Input data. - `estimation-strategy` (keyword): Quantile estimation method used for the median, quartiles, and fence-related statistics, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. Returns a map with the following keys: - `:Size`: number of data points, `count`. - `:Min`: minimum value, see [[minimum]]. - `:Max`: maximum value, see [[maximum]]. - `:Range`: `Max - Min`. - `:Mean`: arithmetic average, see [[mean]]. - `:Median`: middle value, see [[median]]. - `:Mode`: most frequent value, see [[mode]] (default method). - `:Q1`: first quartile (25th percentile), see [[percentile]]. - `:Q3`: third quartile (75th percentile), see [[percentile]]. - `:Total`: sum of all values, see [[sum]]. - `:SD`: sample standard deviation, see [[stddev]]. - `:Variance`: sample variance, `SD^2`, see [[variance]]. - `:MAD`: median absolute deviation, see [[median-absolute-deviation]]. - `:SEM`: standard error of the mean, see [[sem]]. - `:LAV`: lower adjacent value, the smallest value within the lower inner fence, see [[adjacent-values]]. - `:UAV`: upper adjacent value, the largest value within the upper inner fence, see [[adjacent-values]]. - `:IQR`: interquartile range, `Q3 - Q1`. - `:LOF`: lower outer fence, `Q1 - 3*IQR`, see [[outer-fence-extent]]. - `:UOF`: upper outer fence, `Q3 + 3*IQR`, see [[outer-fence-extent]]. - `:LIF`: lower inner fence, `Q1 - 1.5*IQR`, see [[inner-fence-extent]]. - `:UIF`: upper inner fence, `Q3 + 1.5*IQR`, see [[inner-fence-extent]]. - `:Outliers`: sequence of data points falling outside the inner fences, see [[outliers]]. - `:Kurtosis`: measure of tailedness/peakedness, see [[kurtosis]] (default `:G2` type). - `:Skewness`: measure of asymmetry, see [[skewness]] (default `:G1` type). See also [[extent]], [[percentile-extent]], [[adjacent-values]], [[inner-fence-extent]], [[outer-fence-extent]], [[outliers]].
(stddev vs)(stddev vs mu)Calculates the sample (unbiased) standard deviation of vs.
Computed as the square root of variance, i.e. it divides the sum of squared deviations by n-1 (Bessel's correction). Use this version when vs is a sample drawn from a larger population.
Parameters:
vs (sequence of numbers): Input data.mu (double, optional): Precomputed mean of vs. When omitted, the mean is computed from vs.Returns the sample standard deviation as a double.
See also population-stddev, variance, wstddev.
Calculates the sample (unbiased) standard deviation of `vs`. Computed as the square root of [[variance]], i.e. it divides the sum of squared deviations by `n-1` (Bessel's correction). Use this version when `vs` is a sample drawn from a larger population. Parameters: - `vs` (sequence of numbers): Input data. - `mu` (double, optional): Precomputed mean of `vs`. When omitted, the mean is computed from `vs`. Returns the sample standard deviation as a double. See also [[population-stddev]], [[variance]], [[wstddev]].
(stddev-extent vs)Calculates the mean of vs together with its -/+ standard deviation extent.
Parameters:
vs (sequence of numbers): Input data.Returns a 3-element vector [(m/- mean stddev), (m/+ mean stddev), mean].
See also mean, stddev, mad-extent, sem-extent.
Calculates the mean of `vs` together with its `-/+` standard deviation extent. Parameters: - `vs` (sequence of numbers): Input data. Returns a 3-element vector `[(m/- mean stddev), (m/+ mean stddev), mean]`. See also [[mean]], [[stddev]], [[mad-extent]], [[sem-extent]].
(sum vs)(sum vs compensation-method)Calculates the sum of all values in vs.
By default, plain summation is used (an optimized array-specific path for double-array, or a simple reduction otherwise), which is fast but can accumulate floating-point rounding error for long sequences or values of widely differing magnitude. An optional compensated summation algorithm can be selected instead to improve numerical accuracy at the cost of extra computation.
Parameters:
vs (sequence of numbers or double-array): Values to sum.compensation-method (keyword, optional): Compensated summation algorithm. One of :kahan, :neumayer (Neumaier's improved Kahan algorithm) or :klein (second-order compensated summation). Any other value falls back to plain summation.Returns the sum as a double.
Calculates the sum of all values in `vs`. By default, plain summation is used (an optimized array-specific path for `double-array`, or a simple reduction otherwise), which is fast but can accumulate floating-point rounding error for long sequences or values of widely differing magnitude. An optional compensated summation algorithm can be selected instead to improve numerical accuracy at the cost of extra computation. Parameters: - `vs` (sequence of numbers or `double-array`): Values to sum. - `compensation-method` (keyword, optional): Compensated summation algorithm. One of `:kahan`, `:neumayer` (Neumaier's improved Kahan algorithm) or `:klein` (second-order compensated summation). Any other value falls back to plain summation. Returns the sum as a double.
(t-test-one-sample xs)(t-test-one-sample xs m)Performs a one-sample Student's t-test to compare the sample mean against a hypothesized population mean.
This test assesses the null hypothesis that the true population mean is equal to mu.
It is suitable when the population standard deviation is unknown and is estimated
from the sample.
Parameters:
xs (seq of numbers): The sample data.params (map, optional): Options map:
:alpha (double, default 0.05): Significance level for the confidence interval.:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): The true mean is not equal to mu.:one-sided-greater: The true mean is greater than mu.:one-sided-less: The true mean is less than mu.:mu (double, default 0.0): The hypothesized population mean under the null hypothesis.Returns a map containing:
:t: The calculated t-statistic.:stat: Alias for :t.:df: Degrees of freedom (n-1).:p-value: The p-value associated with the t-statistic and :sides.:confidence-interval: Confidence interval for the true population mean.:estimate: The calculated sample mean.:n: The sample size.:mu: The hypothesized population mean used in the test.:stderr: The standard error of the mean (calculated from the sample).:alpha: Significance level used.:sides: Alternative hypothesis side used.:test-type: Alias for :sides.Assumptions:
See also z-test-one-sample for large samples or known population standard deviation.
Performs a one-sample Student's t-test to compare the sample mean against a hypothesized population mean.
This test assesses the null hypothesis that the true population mean is equal to `mu`.
It is suitable when the population standard deviation is unknown and is estimated
from the sample.
Parameters:
- `xs` (seq of numbers): The sample data.
- `params` (map, optional): Options map:
- `:alpha` (double, default `0.05`): Significance level for the confidence interval.
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): The true mean is not equal to `mu`.
- `:one-sided-greater`: The true mean is greater than `mu`.
- `:one-sided-less`: The true mean is less than `mu`.
- `:mu` (double, default `0.0`): The hypothesized population mean under the null hypothesis.
Returns a map containing:
- `:t`: The calculated t-statistic.
- `:stat`: Alias for `:t`.
- `:df`: Degrees of freedom (`n-1`).
- `:p-value`: The p-value associated with the t-statistic and `:sides`.
- `:confidence-interval`: Confidence interval for the true population mean.
- `:estimate`: The calculated sample mean.
- `:n`: The sample size.
- `:mu`: The hypothesized population mean used in the test.
- `:stderr`: The standard error of the mean (calculated from the sample).
- `:alpha`: Significance level used.
- `:sides`: Alternative hypothesis side used.
- `:test-type`: Alias for `:sides`.
Assumptions:
- The data are independent observations.
- The data are drawn from a population that is approximately normally distributed.
(The t-test is relatively robust to moderate violations, especially with larger sample sizes).
See also [[z-test-one-sample]] for large samples or known population standard deviation.(t-test-two-samples xs ys)(t-test-two-samples xs
ys
{:keys [paired? equal-variances?]
:or {paired? false equal-variances? false}
:as params})Performs a two-sample Student's t-test to compare the means of two samples.
This function can perform:
:equal-variances? false): Does not assume equal population variances. Uses the Satterthwaite approximation for degrees of freedom. Recommended unless variances are known to be equal.:equal-variances? true): Assumes equal population variances and uses a pooled variance estimate.:paired? true): Assumes observations in xs and ys are paired (e.g., before/after measurements on the same subjects). This performs a one-sample t-test on the differences between paired observations.The test assesses the null hypothesis that the true difference between the population
means (or the mean of the differences for paired test) is equal to mu.
Parameters:
xs (seq of numbers): The first sample.ys (seq of numbers): The second sample.params (map, optional): Options map:
:alpha (double, default 0.05): Significance level for the confidence interval.:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): The true difference in means is not equal to mu.:one-sided-greater: The true difference (mean(xs) - mean(ys) or mean(diff)) is greater than mu.:one-sided-less: The true difference (mean(xs) - mean(ys) or mean(diff)) is less than mu.:mu (double, default 0.0): The hypothesized difference in means under the null hypothesis.:paired? (boolean, default false): If true, performs a paired t-test (requires xs and ys to have the same length). If false, performs an unpaired test.:equal-variances? (boolean, default false): Used only when paired? is false. If true, assumes equal population variances (Student's). If false, does not assume equal variances (Welch's).Returns a map containing:
:t: The calculated t-statistic.:stat: Alias for :t.:df: Degrees of freedom used for the t-distribution.:p-value: The p-value associated with the t-statistic and :sides.:confidence-interval: Confidence interval for the true difference in means.:estimate: The observed difference between sample means (mean(xs) - mean(ys) or mean(differences)).:n: Sample sizes as [count xs, count ys] (or count diffs if paired).:nx: Sample size of xs (if unpaired).:ny: Sample size of ys (if unpaired).:estimated-mu: Observed sample means as [mean xs, mean ys] (if unpaired).:mu: The hypothesized difference under the null hypothesis.:stderr: The standard error of the difference between the means (or of the mean difference if paired).:alpha: Significance level used.:sides: Alternative hypothesis side used.:test-type: Alias for :sides.:paired?: Boolean indicating if a paired test was performed.:equal-variances?: Boolean indicating the variance assumption used (if unpaired).Assumptions:
:equal-variances? true).Performs a two-sample Student's t-test to compare the means of two samples.
This function can perform:
- An **unpaired t-test** (assuming independent samples) using either:
- **Welch's t-test** (default: `:equal-variances? false`): Does not assume equal population variances. Uses the Satterthwaite approximation for degrees of freedom. Recommended unless variances are known to be equal.
- **Student's t-test** (`:equal-variances? true`): Assumes equal population variances and uses a pooled variance estimate.
- A **paired t-test** (`:paired? true`): Assumes observations in `xs` and `ys` are paired (e.g., before/after measurements on the same subjects). This performs a one-sample t-test on the differences between paired observations.
The test assesses the null hypothesis that the true difference between the population
means (or the mean of the differences for paired test) is equal to `mu`.
Parameters:
- `xs` (seq of numbers): The first sample.
- `ys` (seq of numbers): The second sample.
- `params` (map, optional): Options map:
- `:alpha` (double, default `0.05`): Significance level for the confidence interval.
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): The true difference in means is not equal to `mu`.
- `:one-sided-greater`: The true difference (`mean(xs) - mean(ys)` or `mean(diff)`) is greater than `mu`.
- `:one-sided-less`: The true difference (`mean(xs) - mean(ys)` or `mean(diff)`) is less than `mu`.
- `:mu` (double, default `0.0`): The hypothesized difference in means under the null hypothesis.
- `:paired?` (boolean, default `false`): If `true`, performs a paired t-test (requires `xs` and `ys` to have the same length). If `false`, performs an unpaired test.
- `:equal-variances?` (boolean, default `false`): Used only when `paired?` is `false`. If `true`, assumes equal population variances (Student's). If `false`, does not assume equal variances (Welch's).
Returns a map containing:
- `:t`: The calculated t-statistic.
- `:stat`: Alias for `:t`.
- `:df`: Degrees of freedom used for the t-distribution.
- `:p-value`: The p-value associated with the t-statistic and `:sides`.
- `:confidence-interval`: Confidence interval for the true difference in means.
- `:estimate`: The observed difference between sample means (`mean(xs) - mean(ys)` or `mean(differences)`).
- `:n`: Sample sizes as `[count xs, count ys]` (or `count diffs` if paired).
- `:nx`: Sample size of `xs` (if unpaired).
- `:ny`: Sample size of `ys` (if unpaired).
- `:estimated-mu`: Observed sample means as `[mean xs, mean ys]` (if unpaired).
- `:mu`: The hypothesized difference under the null hypothesis.
- `:stderr`: The standard error of the difference between the means (or of the mean difference if paired).
- `:alpha`: Significance level used.
- `:sides`: Alternative hypothesis side used.
- `:test-type`: Alias for `:sides`.
- `:paired?`: Boolean indicating if a paired test was performed.
- `:equal-variances?`: Boolean indicating the variance assumption used (if unpaired).
Assumptions:
- Independence of observations (within and between groups for unpaired).
- Normality of the underlying populations (or of the differences for paired). The t-test is relatively robust to violations of normality, especially with larger sample sizes.
- Equal variances (only if `:equal-variances? true`).(theils-u group1 group2)(theils-u group1 group2 direction)Calculates Theil's U, the uncertainty coefficient, an entropy-based measure of association between two categorical sequences.
Theil's U normalizes the mutual information (mutual-information) between group1 and group2 by an entropy term, so that (unlike raw mutual information) it always lies within [0.0, 1.0], making it comparable across different pairs of variables. It answers the question: what proportion of one variable's uncertainty is resolved by knowing the other?
Parameters:
group1, group2 (sequences): Two sequences of categorical observations of the same length, paired by index.direction (keyword, optional): Which entropy to normalize by. Defaults to :symmetric.
:symmetric (default): 2 * I(group1;group2) / (H(group1) + H(group2)). A symmetric coefficient, U(group1,group2) = U(group2,group1).:group1: I(group1;group2) / H(group1). The proportion of group1's uncertainty explained by group2 (asymmetric).:group2: I(group1;group2) / H(group2). The proportion of group2's uncertainty explained by group1 (asymmetric).Returns the calculated coefficient as a double, within [0.0, 1.0].
Interpretation:
0.0 indicates no association: the variables are (empirically) independent.1.0 indicates perfect association: the normalizing variable(s) fully determine (or are fully determined by) the other.Corner case: if the entropy used for normalization (H(group1) for :group1, H(group2) for :group2, or both for :symmetric) is 0.0 (i.e. the corresponding sequence has only a single distinct value), the result is NaN (division by zero), matching common implementations (e.g. R's DescTools::UncertCoef).
See also mutual-information, entropy, cramers-v, tschuprows-t, cohens-w (chi-squared-based association measures for comparison).
Calculates Theil's U, the uncertainty coefficient, an entropy-based measure of association between two categorical sequences. Theil's U normalizes the mutual information ([[mutual-information]]) between `group1` and `group2` by an entropy term, so that (unlike raw mutual information) it always lies within `[0.0, 1.0]`, making it comparable across different pairs of variables. It answers the question: what proportion of one variable's uncertainty is resolved by knowing the other? Parameters: - `group1`, `group2` (sequences): Two sequences of categorical observations of the same length, paired by index. - `direction` (keyword, optional): Which entropy to normalize by. Defaults to `:symmetric`. - `:symmetric` (default): `2 * I(group1;group2) / (H(group1) + H(group2))`. A symmetric coefficient, `U(group1,group2) = U(group2,group1)`. - `:group1`: `I(group1;group2) / H(group1)`. The proportion of `group1`'s uncertainty explained by `group2` (asymmetric). - `:group2`: `I(group1;group2) / H(group2)`. The proportion of `group2`'s uncertainty explained by `group1` (asymmetric). Returns the calculated coefficient as a double, within `[0.0, 1.0]`. Interpretation: - `0.0` indicates no association: the variables are (empirically) independent. - `1.0` indicates perfect association: the normalizing variable(s) fully determine (or are fully determined by) the other. Corner case: if the entropy used for normalization (`H(group1)` for `:group1`, `H(group2)` for `:group2`, or both for `:symmetric`) is `0.0` (i.e. the corresponding sequence has only a single distinct value), the result is `NaN` (division by zero), matching common implementations (e.g. R's `DescTools::UncertCoef`). See also [[mutual-information]], [[entropy]], [[cramers-v]], [[tschuprows-t]], [[cohens-w]] (chi-squared-based association measures for comparison).
(trim vs)(trim vs quantile)(trim vs quantile estimation-strategy)(trim vs low high nan)Trims vs, discarding values falling outside a pair of quantile-based bounds.
Unlike winsor, which clamps out-of-bound values, this function removes them entirely, so the resulting sequence may be shorter than vs. NaN entries are always kept but replaced by a given replacement value (the median, unless given explicitly).
Parameters:
vs (sequence of numbers): Input data.quantile (double): Trimming proportion applied to each tail, e.g. 0.2 discards the bottom 20% and top 20% of the data, below the 20th and above the 80th percentile. Defaults to 0.2.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.low, high (doubles): Explicit lower and upper bounds, used instead of computing them from quantile. Order does not matter, the smaller value is always used as the lower bound.nan (double): Replacement value for NaN entries in vs.Returns a lazy sequence containing only the values from vs within [low,high], with NaN values replaced.
See also trim-lower, trim-upper, winsor, remove-outliers, quantile.
Trims `vs`, discarding values falling outside a pair of quantile-based bounds. Unlike [[winsor]], which clamps out-of-bound values, this function removes them entirely, so the resulting sequence may be shorter than `vs`. `NaN` entries are always kept but replaced by a given replacement value (the median, unless given explicitly). Parameters: - `vs` (sequence of numbers): Input data. - `quantile` (double): Trimming proportion applied to each tail, e.g. `0.2` discards the bottom 20% and top 20% of the data, below the 20th and above the 80th percentile. Defaults to `0.2`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. - `low`, `high` (doubles): Explicit lower and upper bounds, used instead of computing them from `quantile`. Order does not matter, the smaller value is always used as the lower bound. - `nan` (double): Replacement value for `NaN` entries in `vs`. Returns a lazy sequence containing only the values from `vs` within `[low,high]`, with `NaN` values replaced. See also [[trim-lower]], [[trim-upper]], [[winsor]], [[remove-outliers]], [[quantile]].
(trim-lower vs)(trim-lower vs quantile)(trim-lower vs quantile estimation-strategy)Trims vs, discarding values below a given quantile.
This is a one-sided version of trim: only values below the cutoff are discarded, values above it are all kept.
Parameters:
vs (sequence of numbers): Input data.quantile (double): Trimming proportion, e.g. 0.2 discards values below the 20th percentile. Defaults to 0.2.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.NaN entries are always kept but replaced by the median of vs.
Returns a lazy sequence containing only the values from vs at or above the cutoff quantile, with NaN values replaced.
See also trim-upper, trim, winsor.
Trims `vs`, discarding values below a given quantile. This is a one-sided version of [[trim]]: only values below the cutoff are discarded, values above it are all kept. Parameters: - `vs` (sequence of numbers): Input data. - `quantile` (double): Trimming proportion, e.g. `0.2` discards values below the 20th percentile. Defaults to `0.2`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. `NaN` entries are always kept but replaced by the median of `vs`. Returns a lazy sequence containing only the values from `vs` at or above the cutoff quantile, with `NaN` values replaced. See also [[trim-upper]], [[trim]], [[winsor]].
(trim-upper vs)(trim-upper vs quantile)(trim-upper vs quantile estimation-strategy)Trims vs, discarding values above a given quantile.
This is a one-sided version of trim: only values above the cutoff are discarded, values below it are all kept.
Parameters:
vs (sequence of numbers): Input data.quantile (double): Trimming proportion, e.g. 0.2 discards values above the 80th percentile (1.0-quantile). Defaults to 0.2.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.NaN entries are always kept but replaced by the median of vs.
Returns a lazy sequence containing only the values from vs at or below the cutoff quantile, with NaN values replaced.
See also trim-lower, trim, winsor.
Trims `vs`, discarding values above a given quantile. This is a one-sided version of [[trim]]: only values above the cutoff are discarded, values below it are all kept. Parameters: - `vs` (sequence of numbers): Input data. - `quantile` (double): Trimming proportion, e.g. `0.2` discards values above the 80th percentile (`1.0-quantile`). Defaults to `0.2`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. `NaN` entries are always kept but replaced by the median of `vs`. Returns a lazy sequence containing only the values from `vs` at or below the cutoff quantile, with `NaN` values replaced. See also [[trim-lower]], [[trim]], [[winsor]].
(tschuprows-t contingency-table)(tschuprows-t group1 group2)Calculates Tschuprow's T, a measure of association between two nominal variables represented in a contingency table.
Tschuprow's T is derived from the Pearson's Chi-squared statistic and measures the strength of the association. Its value ranges from 0 to 1.
r) equals the number of columns (k) in the contingency table. If r != k,
Tschuprow's T cannot reach 1, making Cramer's V (cramers-v) often preferred
as it can reach 1 for any table size.The function can be called in two ways:
group1 and group2:
The function will automatically construct a contingency table from
the unique values in the sequences.[row-index, column-index] tuples and values are counts
(e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This is the output format
of contingency-table with two inputs.[[10 5] [3 12]]). This is equivalent to rows->contingency-table.Parameters:
group1 (sequence): The first sequence of categorical data.group2 (sequence): The second sequence of categorical data. Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed contingency table.Returns the calculated Tschuprow's T coefficient as a double.
See also chisq-test, cramers-c, cramers-v, cohens-w, contingency-table.
Calculates Tschuprow's T, a measure of association between two nominal variables
represented in a contingency table.
Tschuprow's T is derived from the Pearson's Chi-squared statistic and measures
the strength of the association. Its value ranges from 0 to 1.
- A value of 0 indicates no association between the variables.
- A value of 1 indicates perfect association, but only when the number of rows
(`r`) equals the number of columns (`k`) in the contingency table. If `r != k`,
Tschuprow's T cannot reach 1, making Cramer's V ([[cramers-v]]) often preferred
as it can reach 1 for any table size.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a contingency table from
the unique values in the sequences.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This is the output format
of [[contingency-table]] with two inputs.
- A sequence of sequences representing the rows of the table
(e.g., `[[10 5] [3 12]]`). This is equivalent to [[rows->contingency-table]].
Parameters:
- `group1` (sequence): The first sequence of categorical data.
- `group2` (sequence): The second sequence of categorical data. Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed contingency table.
Returns the calculated Tschuprow's T coefficient as a double.
See also [[chisq-test]], [[cramers-c]], [[cramers-v]], [[cohens-w]], [[contingency-table]].(variance vs)(variance vs mu)Calculates the sample (unbiased) variance of vs.
The sum of squared deviations from the mean is divided by n-1 (Bessel's correction), where n is the number of observations. Use this version when vs is a sample drawn from a larger population; for the biased version dividing by n, see population-variance.
Parameters:
vs (sequence of numbers): Input data.mu (double, optional): Precomputed mean of vs. When omitted, the mean is computed from vs.Returns the sample variance as a double.
See also population-variance, stddev, wvariance.
Calculates the sample (unbiased) variance of `vs`. The sum of squared deviations from the mean is divided by `n-1` (Bessel's correction), where `n` is the number of observations. Use this version when `vs` is a sample drawn from a larger population; for the biased version dividing by `n`, see [[population-variance]]. Parameters: - `vs` (sequence of numbers): Input data. - `mu` (double, optional): Precomputed mean of `vs`. When omitted, the mean is computed from `vs`. Returns the sample variance as a double. See also [[population-variance]], [[stddev]], [[wvariance]].
(variation vs)Calculates the coefficient of variation (CV) for a sequence vs.
The CV is a standardized measure of dispersion of a probability distribution or frequency distribution. It is defined as the ratio of the standard deviation to the mean:
CV = stddev(vs) / mean(vs)
This measure is unitless and allows for comparison of variability between datasets with different means or different units.
Parameters:
vs: Sequence of numbers.Returns the calculated coefficient of variation as a double.
Note: The CV is undefined if the mean is zero, and may be misleading if the
mean is close to zero or if the data can take both positive and negative values.
All values in vs should ideally be positive.
Calculates the coefficient of variation (CV) for a sequence `vs`. The CV is a standardized measure of dispersion of a probability distribution or frequency distribution. It is defined as the ratio of the standard deviation to the mean: `CV = stddev(vs) / mean(vs)` This measure is unitless and allows for comparison of variability between datasets with different means or different units. Parameters: - `vs`: Sequence of numbers. Returns the calculated coefficient of variation as a double. Note: The CV is undefined if the mean is zero, and may be misleading if the mean is close to zero or if the data can take both positive and negative values. All values in `vs` should ideally be positive. See also [[stddev]], [[mean]].
(weighted-kappa contingency-table)(weighted-kappa contingency-table weights)Calculates Cohen's weighted Kappa coefficient (κ) for a contingency table, allowing for partial agreement between categories, typically used for ordinal data.
Weighted Kappa measures inter-rater agreement, similar to cohens-kappa,
but assigns different penalties to disagreements based on their magnitude.
Disagreements between closely related categories are penalized less than
disagreements between distantly related categories.
The function can be called in two ways:
With two sequences group1 and group2:
The function will automatically construct a contingency table from
the unique values in the sequences. These values are assumed to be ordinal
and their position in the sorted unique value list determines their index.
The mapping of values to table indices might need verification.
With a contingency table: The contingency table can be provided as:
[row-index, column-index] tuples and values are counts
(e.g., {[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}). This is the output format
of contingency-table with two inputs. Indices are assumed to represent
the ordered categories.[[10 5] [3 12]]). This is equivalent to rows->contingency-table.
The row and column indices are assumed to correspond to the ordered categories.Parameters:
group1 (sequence): The first sequence of ordinal outcomes/categories.group2 (sequence): The second sequence of ordinal outcomes/categories.
Must have the same length as group1.contingency-table (map or sequence of sequences): A pre-computed contingency table
where row and column indices correspond to ordered categories.weights (keyword, function, or map, optional): Specifies the weighting scheme
to quantify the difference between categories. Defaults to :equal-spacing.
:equal-spacing (default, linear weights): Penalizes disagreements linearly
with the distance between categories. Weight is 1 - |i-j|/R, where i is
row index, j is column index, and R is the maximum dimension of the table (max(max_row_index, max_col_index)).:fleiss-cohen (quadratic weights): Penalizes disagreements quadratically
with the distance. Weight is 1 - (|i-j|/R)^2.(fn [R id1 id2])): A custom function that takes the maximum
dimension R, row index id1, and column index id2 and returns the weight
(typically between 0 and 1, where 1 is perfect agreement).{[id1 id2] weight}): A custom map providing weights for specific
[row-index, column-index] pairs. Missing pairs default to a weight of 0.0.Returns the calculated weighted Cohen's Kappa coefficient as a double.
Interpretation:
κ_w = 1: Perfect agreement.κ_w = 0: Agreement is no better than chance.κ_w < 0: Agreement is worse than chance.See also cohens-kappa (unweighted Kappa).
Calculates Cohen's weighted Kappa coefficient (κ) for a contingency table,
allowing for partial agreement between categories, typically used for ordinal data.
Weighted Kappa measures inter-rater agreement, similar to [[cohens-kappa]],
but assigns different penalties to disagreements based on their magnitude.
Disagreements between closely related categories are penalized less than
disagreements between distantly related categories.
The function can be called in two ways:
1. With two sequences `group1` and `group2`:
The function will automatically construct a contingency table from
the unique values in the sequences. These values are assumed to be ordinal
and their position in the sorted unique value list determines their index.
The mapping of values to table indices might need verification.
2. With a contingency table:
The contingency table can be provided as:
- A map where keys are `[row-index, column-index]` tuples and values are counts
(e.g., `{[0 0] 10, [0 1] 5, [1 0] 3, [1 1] 12}`). This is the output format
of [[contingency-table]] with two inputs. Indices are assumed to represent
the ordered categories.
- A sequence of sequences representing the rows of the table
(e.g., `[[10 5] [3 12]]`). This is equivalent to [[rows->contingency-table]].
The row and column indices are assumed to correspond to the ordered categories.
Parameters:
- `group1` (sequence): The first sequence of ordinal outcomes/categories.
- `group2` (sequence): The second sequence of ordinal outcomes/categories.
Must have the same length as `group1`.
- `contingency-table` (map or sequence of sequences): A pre-computed contingency table
where row and column indices correspond to ordered categories.
- `weights` (keyword, function, or map, optional): Specifies the weighting scheme
to quantify the difference between categories. Defaults to `:equal-spacing`.
- `:equal-spacing` (default, linear weights): Penalizes disagreements linearly
with the distance between categories. Weight is `1 - |i-j|/R`, where `i` is
row index, `j` is column index, and `R` is the maximum dimension of the table (max(max_row_index, max_col_index)).
- `:fleiss-cohen` (quadratic weights): Penalizes disagreements quadratically
with the distance. Weight is `1 - (|i-j|/R)^2`.
- (function `(fn [R id1 id2])`): A custom function that takes the maximum
dimension `R`, row index `id1`, and column index `id2` and returns the weight
(typically between 0 and 1, where 1 is perfect agreement).
- (map `{[id1 id2] weight}`): A custom map providing weights for specific
`[row-index, column-index]` pairs. Missing pairs default to a weight of 0.0.
Returns the calculated weighted Cohen's Kappa coefficient as a double.
Interpretation:
- `κ_w = 1`: Perfect agreement.
- `κ_w = 0`: Agreement is no better than chance.
- `κ_w < 0`: Agreement is worse than chance.
See also [[cohens-kappa]] (unweighted Kappa).(winsor vs)(winsor vs quantile)(winsor vs quantile estimation-strategy)(winsor vs low high nan)Winsorizes vs, clamping extreme values to a pair of quantile-based bounds.
Values below the lower bound are replaced by the lower bound, and values above the upper bound are replaced by the upper bound, so the size of the sequence is unchanged. NaN entries are always replaced by a given replacement value (the median, unless given explicitly).
Parameters:
vs (sequence of numbers): Input data.quantile (double): Trimming proportion applied to each tail, e.g. 0.2 clamps the bottom 20% and top 20% of the data to the 20th and 80th percentile values respectively. Defaults to 0.2.estimation-strategy (keyword): Quantile estimation method, one of the keys of estimation-strategies-list. Defaults to :legacy.low, high (doubles): Explicit lower and upper bounds, used instead of computing them from quantile. Order does not matter, the smaller value is always used as the lower bound.nan (double): Replacement value for NaN entries in vs.Returns a lazy sequence of the same length as vs, with out-of-bound values clamped and NaN values replaced.
See also trim, remove-outliers, quantile.
Winsorizes `vs`, clamping extreme values to a pair of quantile-based bounds. Values below the lower bound are replaced by the lower bound, and values above the upper bound are replaced by the upper bound, so the size of the sequence is unchanged. `NaN` entries are always replaced by a given replacement value (the median, unless given explicitly). Parameters: - `vs` (sequence of numbers): Input data. - `quantile` (double): Trimming proportion applied to each tail, e.g. `0.2` clamps the bottom 20% and top 20% of the data to the 20th and 80th percentile values respectively. Defaults to `0.2`. - `estimation-strategy` (keyword): Quantile estimation method, one of the keys of [[estimation-strategies-list]]. Defaults to `:legacy`. - `low`, `high` (doubles): Explicit lower and upper bounds, used instead of computing them from `quantile`. Order does not matter, the smaller value is always used as the lower bound. - `nan` (double): Replacement value for `NaN` entries in `vs`. Returns a lazy sequence of the same length as `vs`, with out-of-bound values clamped and `NaN` values replaced. See also [[trim]], [[remove-outliers]], [[quantile]].
(wmedian vs ws)(wmedian vs ws method)Calculates median of a sequence vs with corresponding weights ws.
Parameters:
vs: Sequence of data values.ws: Sequence of corresponding non-negative weights. Must have the same count as vs.method (optional keyword): Specifies the interpolation method used when qs falls
between points in the weighted ECDF. Defaults to :linear.
:linear: Performs linear interpolation between the data values corresponding
to the cumulative weights surrounding q=0.5.:step: Uses a step function (specifically, step-before) based on the
weighted ECDF. The result is the data value whose cumulative weight range
includes q=0.5.:average: Computes the average of the step-before and step-after
interpolation methods.Calculates median of a sequence `vs` with corresponding weights `ws`.
Parameters:
- `vs`: Sequence of data values.
- `ws`: Sequence of corresponding non-negative weights. Must have the same count as `vs`.
- `method` (optional keyword): Specifies the interpolation method used when `qs` falls
between points in the weighted ECDF. Defaults to `:linear`.
- `:linear`: Performs linear interpolation between the data values corresponding
to the cumulative weights surrounding `q=0.5`.
- `:step`: Uses a step function (specifically, step-before) based on the
weighted ECDF. The result is the data value whose cumulative weight range
includes `q=0.5`.
- `:average`: Computes the average of the step-before and step-after
interpolation methods.
See also: [[wquantile]], [[quantile]].(wmode vs)(wmode vs weights)Returns the primary weighted mode of a sequence vs.
The mode is the value that appears most often in a dataset. This function generalizes the mode concept by considering weights associated with each value. A value's contribution to the mode calculation is proportional to its weight.
If multiple values share the same highest total weight (i.e., there are ties
for the mode), this function returns only the first one encountered during
processing. The specific mode returned in case of a tie is not guaranteed
to be stable across different runs or environments. Use wmodes if you
need all tied modes.
Parameters:
vs: Sequence of data values. Can contain any data type (numbers, keywords, etc.).weights (optional): Sequence of non-negative weights corresponding to vs.
Must have the same count as vs. Defaults to a sequence of 1.0s if omitted,
effectively calculating the unweighted mode.Returns a single value representing the mode (or one of the modes if ties exist).
See also wmodes (returns all modes) and mode (for unweighted numeric data).
Returns the primary weighted mode of a sequence `vs`. The mode is the value that appears most often in a dataset. This function generalizes the mode concept by considering weights associated with each value. A value's contribution to the mode calculation is proportional to its weight. If multiple values share the same highest total weight (i.e., there are ties for the mode), this function returns only the first one encountered during processing. The specific mode returned in case of a tie is not guaranteed to be stable across different runs or environments. Use [[wmodes]] if you need all tied modes. Parameters: - `vs`: Sequence of data values. Can contain any data type (numbers, keywords, etc.). - `weights` (optional): Sequence of non-negative weights corresponding to `vs`. Must have the same count as `vs`. Defaults to a sequence of 1.0s if omitted, effectively calculating the unweighted mode. Returns a single value representing the mode (or one of the modes if ties exist). See also [[wmodes]] (returns all modes) and [[mode]] (for unweighted numeric data).
(wmodes vs)(wmodes vs weights)Returns the weighted mode(s) of a sequence vs.
The mode is the value that appears most often in a dataset. This function generalizes the mode concept by considering weights associated with each value. A value's contribution to the mode calculation is proportional to its weight.
Parameters:
vs: Sequence of data values. Can contain any data type (numbers, keywords, etc.).weights (optional): Sequence of non-negative weights corresponding to vs.
Must have the same count as vs. Defaults to a sequence of 1.0s if omitted,
effectively calculating the unweighted modes.Returns a sequence containing all values that have the highest total weight. If there are ties (multiple values share the same maximum total weight), all tied values are included in the returned sequence. The order of modes in the returned sequence is not guaranteed.
See also wmode (returns only one mode in case of ties) and modes (for unweighted numeric data).
Returns the weighted mode(s) of a sequence `vs`. The mode is the value that appears most often in a dataset. This function generalizes the mode concept by considering weights associated with each value. A value's contribution to the mode calculation is proportional to its weight. Parameters: - `vs`: Sequence of data values. Can contain any data type (numbers, keywords, etc.). - `weights` (optional): Sequence of non-negative weights corresponding to `vs`. Must have the same count as `vs`. Defaults to a sequence of 1.0s if omitted, effectively calculating the unweighted modes. Returns a sequence containing all values that have the highest total weight. If there are ties (multiple values share the same maximum total weight), all tied values are included in the returned sequence. The order of modes in the returned sequence is not guaranteed. See also [[wmode]] (returns only one mode in case of ties) and [[modes]] (for unweighted numeric data).
(wmw-odds [group1 group2])(wmw-odds group1 group2)Calculates the Wilcoxon-Mann-Whitney odds (often denoted as ψ) for two independent samples.
This non-parametric effect size measure quantifies the odds that a randomly chosen
observation from the first group (group1) is greater than a randomly chosen
observation from the second group (group2).
The statistic is directly related to cliffs-delta (δ): ψ = (1 + δ) / (1 - δ).
Parameters:
group1 (seq of numbers): The first independent sample.group2 (seq of numbers): The second independent sample.Returns the calculated WMW odds as a double.
Interpretation:
group1 tend to be larger than values from group2.group1 tend to be smaller than values from group2.This measure is robust to violations of normality and is suitable for ordinal data. It is closely related to Cliff's Delta (δ) and the Mann-Whitney U test statistic.
See also cliffs-delta, ameasure.
Calculates the Wilcoxon-Mann-Whitney odds (often denoted as ψ) for two independent samples. This non-parametric effect size measure quantifies the odds that a randomly chosen observation from the first group (`group1`) is greater than a randomly chosen observation from the second group (`group2`). The statistic is directly related to [[cliffs-delta]] (δ): ψ = (1 + δ) / (1 - δ). Parameters: - `group1` (seq of numbers): The first independent sample. - `group2` (seq of numbers): The second independent sample. Returns the calculated WMW odds as a double. Interpretation: - A value greater than 1 indicates that values from `group1` tend to be larger than values from `group2`. - A value less than 1 indicates that values from `group1` tend to be smaller than values from `group2`. - A value of 1 indicates stochastic equality between the distributions (50/50 odds). This measure is robust to violations of normality and is suitable for ordinal data. It is closely related to Cliff's Delta (δ) and the Mann-Whitney U test statistic. See also [[cliffs-delta]], [[ameasure]].
(wquantile vs ws q)(wquantile vs ws q method)Calculates the q-th weighted quantile of a sequence vs with corresponding weights ws.
The quantile q is a value between 0.0 and 1.0, inclusive.
The calculation involves constructing a weighted empirical cumulative distribution
function (ECDF) and interpolating to find the value at quantile q.
Parameters:
vs: Sequence of data values.ws: Sequence of corresponding non-negative weights. Must have the same count as vs.q: The quantile level (0.0 < q <= 1.0).method (optional keyword): Specifies the interpolation method used when q falls
between points in the weighted ECDF. Defaults to :linear.
:linear: Performs linear interpolation between the data values corresponding
to the cumulative weights surrounding q.:step: Uses a step function (specifically, step-before) based on the
weighted ECDF. The result is the data value whose cumulative weight range
includes q.:average: Computes the average of the step-before and step-after
interpolation methods. Useful when q corresponds exactly to a cumulative
weight boundary.See also: wmedian, wquantiles, quantile.
Calculates the q-th weighted quantile of a sequence `vs` with corresponding weights `ws`.
The quantile `q` is a value between 0.0 and 1.0, inclusive.
The calculation involves constructing a weighted empirical cumulative distribution
function (ECDF) and interpolating to find the value at quantile `q`.
Parameters:
- `vs`: Sequence of data values.
- `ws`: Sequence of corresponding non-negative weights. Must have the same count as `vs`.
- `q`: The quantile level (0.0 < q <= 1.0).
- `method` (optional keyword): Specifies the interpolation method used when `q` falls
between points in the weighted ECDF. Defaults to `:linear`.
- `:linear`: Performs linear interpolation between the data values corresponding
to the cumulative weights surrounding `q`.
- `:step`: Uses a step function (specifically, step-before) based on the
weighted ECDF. The result is the data value whose cumulative weight range
includes `q`.
- `:average`: Computes the average of the step-before and step-after
interpolation methods. Useful when `q` corresponds exactly to a cumulative
weight boundary.
See also: [[wmedian]], [[wquantiles]], [[quantile]].(wquantiles vs ws)(wquantiles vs ws qs)(wquantiles vs ws qs method)Calculates the sequence of q-th weighted quantiles of a sequence vs with corresponding weights ws.
Quantiles qs is a sequence of values between 0.0 and 1.0, inclusive.
The calculation involves constructing a weighted empirical cumulative distribution
function (ECDF) and interpolating to find the value at quantiles qs.
Parameters:
vs: Sequence of data values.ws: Sequence of corresponding non-negative weights. Must have the same count as vs.qs: Sequence of quantiles level (0.0 < q <= 1.0).method (optional keyword): Specifies the interpolation method used when qs falls
between points in the weighted ECDF. Defaults to :linear.
:linear: Performs linear interpolation between the data values corresponding
to the cumulative weights surrounding q.:step: Uses a step function (specifically, step-before) based on the
weighted ECDF. The result is the data value whose cumulative weight range
includes q.:average: Computes the average of the step-before and step-after
interpolation methods. Useful when q corresponds exactly to a cumulative
weight boundary.Calculates the sequence of q-th weighted quantiles of a sequence `vs` with corresponding weights `ws`.
Quantiles `qs` is a sequence of values between 0.0 and 1.0, inclusive.
The calculation involves constructing a weighted empirical cumulative distribution
function (ECDF) and interpolating to find the value at quantiles `qs`.
Parameters:
- `vs`: Sequence of data values.
- `ws`: Sequence of corresponding non-negative weights. Must have the same count as `vs`.
- `qs`: Sequence of quantiles level (0.0 < q <= 1.0).
- `method` (optional keyword): Specifies the interpolation method used when `qs` falls
between points in the weighted ECDF. Defaults to `:linear`.
- `:linear`: Performs linear interpolation between the data values corresponding
to the cumulative weights surrounding `q`.
- `:step`: Uses a step function (specifically, step-before) based on the
weighted ECDF. The result is the data value whose cumulative weight range
includes `q`.
- `:average`: Computes the average of the step-before and step-after
interpolation methods. Useful when `q` corresponds exactly to a cumulative
weight boundary.
See also: [[wquantile]], [[quantiles]].(wstddev vs freqs)Calculates the weighted sample (unbiased) standard deviation of vs.
Computed as the square root of wvariance, i.e. each value is weighted by the corresponding entry in freqs and the sum of squared deviations is divided by (sum freqs) - 1.
Parameters:
vs (sequence of numbers): Input data.freqs (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in vs, same length as vs.Returns the weighted sample standard deviation as a double.
See also population-wstddev, wvariance, stddev.
Calculates the weighted sample (unbiased) standard deviation of `vs`. Computed as the square root of [[wvariance]], i.e. each value is weighted by the corresponding entry in `freqs` and the sum of squared deviations is divided by `(sum freqs) - 1`. Parameters: - `vs` (sequence of numbers): Input data. - `freqs` (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in `vs`, same length as `vs`. Returns the weighted sample standard deviation as a double. See also [[population-wstddev]], [[wvariance]], [[stddev]].
(wvariance vs freqs)Calculates the weighted sample (unbiased) variance of vs.
Each value is weighted by the corresponding entry in freqs, and the weighted sum of squared deviations from the weighted mean is divided by (sum freqs) - 1. This is the weighted analogue of variance; for the biased version dividing by (sum freqs), see population-wvariance.
Parameters:
vs (sequence of numbers): Input data.freqs (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in vs, same length as vs.Returns the weighted sample variance as a double.
See also population-wvariance, variance, wstddev.
Calculates the weighted sample (unbiased) variance of `vs`. Each value is weighted by the corresponding entry in `freqs`, and the weighted sum of squared deviations from the weighted mean is divided by `(sum freqs) - 1`. This is the weighted analogue of [[variance]]; for the biased version dividing by `(sum freqs)`, see [[population-wvariance]]. Parameters: - `vs` (sequence of numbers): Input data. - `freqs` (sequence of numbers): Weights (e.g. frequencies) corresponding to each value in `vs`, same length as `vs`. Returns the weighted sample variance as a double. See also [[population-wvariance]], [[variance]], [[wstddev]].
(yeo-johnson-infer-lambda xs)(yeo-johnson-infer-lambda xs lambda-range)(yeo-johnson-infer-lambda xs lambda-range {:keys [alpha] :or {alpha 0.0}})Find optimal lambda parameter for Yeo-Johnson tranformation using maximum log likelihood method.
Find optimal `lambda` parameter for Yeo-Johnson tranformation using maximum log likelihood method.
(yeo-johnson-transformation xs)(yeo-johnson-transformation xs lambda)(yeo-johnson-transformation xs lambda {:keys [alpha inverse?] :or {alpha 0.0}})Applies the Yeo-Johnson transformation to a dataset.
This transformation is used to stabilize variance and make data more normally distributed. It extends the Box-Cox transformation to allow for zero and negative values.
Parameters:
xs: The input dataset.lambda (default: 0.0): The power parameter controlling the transformation. If lambda is nil or a range [lambda-min, lambda-max] it will be inferred using maximum log-likelihood method.:alpha (optional): A shift parameter applied before transformation.:inverse? (optional): Perform inverse operation, lambda should be provided (can't be inferred).Returns:
Related: box-cox-tranformation
Applies the Yeo-Johnson transformation to a dataset. This transformation is used to stabilize variance and make data more normally distributed. It extends the Box-Cox transformation to allow for zero and negative values. Parameters: - `xs`: The input dataset. - `lambda` (default: 0.0): The power parameter controlling the transformation. If `lambda` is `nil` or a range `[lambda-min, lambda-max]` it will be inferred using maximum log-likelihood method. - Options map: - `:alpha` (optional): A shift parameter applied before transformation. - `:inverse?` (optional): Perform inverse operation, `lambda` should be provided (can't be inferred). Returns: - A transformed sequence of numbers. Related: `box-cox-tranformation`
(z-test-one-sample xs)(z-test-one-sample xs m)Performs a one-sample Z-test to compare the sample mean against a hypothesized population mean.
This test assesses the null hypothesis that the true population mean is equal to mu.
It typically assumes either a known population standard deviation or relies on a
large sample size (e.g., n > 30) where the sample standard deviation provides a
reliable estimate. This implementation uses the sample standard deviation to calculate
the standard error.
Parameters:
xs (seq of numbers): The sample data.params (map, optional): Options map:
:alpha (double, default 0.05): Significance level for the confidence interval.:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): The true mean is not equal to mu.:one-sided-greater: The true mean is greater than mu.:one-sided-less: The true mean is less than mu.:mu (double, default 0.0): The hypothesized population mean under the null hypothesis.Returns a map containing:
:z: The calculated Z-statistic.:stat: Alias for :z.:p-value: The p-value associated with the Z-statistic and the specified :sides.:confidence-interval: Confidence interval for the true population mean.:estimate: The calculated sample mean.:n: The sample size.:mu: The hypothesized population mean used in the test.:stderr: The standard error of the mean (calculated using sample standard deviation).:alpha: Significance level used.:sides: Alternative hypothesis side used.:test-type: Alias for :sides.See also t-test-one-sample for smaller samples or when the population standard deviation is unknown.
Performs a one-sample Z-test to compare the sample mean against a hypothesized population mean.
This test assesses the null hypothesis that the true population mean is equal to `mu`.
It typically assumes either a known population standard deviation or relies on a
large sample size (e.g., n > 30) where the sample standard deviation provides a
reliable estimate. This implementation uses the sample standard deviation to calculate
the standard error.
Parameters:
- `xs` (seq of numbers): The sample data.
- `params` (map, optional): Options map:
- `:alpha` (double, default `0.05`): Significance level for the confidence interval.
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): The true mean is not equal to `mu`.
- `:one-sided-greater`: The true mean is greater than `mu`.
- `:one-sided-less`: The true mean is less than `mu`.
- `:mu` (double, default `0.0`): The hypothesized population mean under the null hypothesis.
Returns a map containing:
- `:z`: The calculated Z-statistic.
- `:stat`: Alias for `:z`.
- `:p-value`: The p-value associated with the Z-statistic and the specified `:sides`.
- `:confidence-interval`: Confidence interval for the true population mean.
- `:estimate`: The calculated sample mean.
- `:n`: The sample size.
- `:mu`: The hypothesized population mean used in the test.
- `:stderr`: The standard error of the mean (calculated using sample standard deviation).
- `:alpha`: Significance level used.
- `:sides`: Alternative hypothesis side used.
- `:test-type`: Alias for `:sides`.
See also [[t-test-one-sample]] for smaller samples or when the population standard deviation is unknown.(z-test-two-samples xs ys)(z-test-two-samples xs
ys
{:keys [paired? equal-variances?]
:or {paired? false equal-variances? false}
:as params})Performs a two-sample Z-test to compare the means of two independent or paired samples.
This test assesses the null hypothesis that the difference between the population
means is equal to mu (default 0). It typically assumes known population variances
or relies on large sample sizes where sample variances provide good estimates.
This implementation calculates the standard error using the provided sample variances.
Parameters:
xs (seq of numbers): The first sample.ys (seq of numbers): The second sample.params (map, optional): Options map:
:alpha (double, default 0.05): Significance level for the confidence interval.:sides (keyword, default :two-sided): Specifies the alternative hypothesis.
:two-sided (default): The true difference in means is not equal to mu.:one-sided-greater: The true difference in means (mean(xs) - mean(ys)) is greater than mu.:one-sided-less: The true difference in means (mean(xs) - mean(ys)) is less than mu.:mu (double, default 0.0): The hypothesized difference in means under the null hypothesis.:paired? (boolean, default false): If true, performs a paired Z-test by applying z-test-one-sample to the differences between paired observations in xs and ys (requires xs and ys to have the same length). If false, performs a two-sample test assuming independence.:equal-variances? (boolean, default false): Used only when paired? is false. If true, assumes population variances are equal and calculates a pooled standard error. If false, calculates the standard error without assuming equal variances (Welch's approach adapted for Z-test). This affects the standard error calculation but the standard normal distribution is still used for inference.Returns a map containing:
:z: The calculated Z-statistic.:stat: Alias for :z.:p-value: The p-value associated with the Z-statistic and the specified :sides.:confidence-interval: Confidence interval for the true difference in means.:estimate: The observed difference between sample means (mean(xs) - mean(ys)).:n: Sample sizes as [count xs, count ys].:nx: Sample size of xs.:ny: Sample size of ys.:estimated-mu: The observed sample means as [mean xs, mean ys].:mu: The hypothesized difference under the null hypothesis.:stderr: The standard error of the difference between the means.:alpha: Significance level used.:sides: Alternative hypothesis side used.:test-type: Alias for :sides.:paired?: Boolean indicating if a paired test was performed.:equal-variances?: Boolean indicating the assumption used for standard error calculation (if unpaired).See also t-test-two-samples for smaller samples or when population variances are unknown.
Performs a two-sample Z-test to compare the means of two independent or paired samples.
This test assesses the null hypothesis that the difference between the population
means is equal to `mu` (default 0). It typically assumes known population variances
or relies on large sample sizes where sample variances provide good estimates.
This implementation calculates the standard error using the provided sample variances.
Parameters:
- `xs` (seq of numbers): The first sample.
- `ys` (seq of numbers): The second sample.
- `params` (map, optional): Options map:
- `:alpha` (double, default `0.05`): Significance level for the confidence interval.
- `:sides` (keyword, default `:two-sided`): Specifies the alternative hypothesis.
- `:two-sided` (default): The true difference in means is not equal to `mu`.
- `:one-sided-greater`: The true difference in means (`mean(xs) - mean(ys)`) is greater than `mu`.
- `:one-sided-less`: The true difference in means (`mean(xs) - mean(ys)`) is less than `mu`.
- `:mu` (double, default `0.0`): The hypothesized difference in means under the null hypothesis.
- `:paired?` (boolean, default `false`): If `true`, performs a paired Z-test by applying [[z-test-one-sample]] to the differences between paired observations in `xs` and `ys` (requires `xs` and `ys` to have the same length). If `false`, performs a two-sample test assuming independence.
- `:equal-variances?` (boolean, default `false`): Used only when `paired?` is `false`. If `true`, assumes population variances are equal and calculates a pooled standard error. If `false`, calculates the standard error without assuming equal variances (Welch's approach adapted for Z-test). This affects the standard error calculation but the standard normal distribution is still used for inference.
Returns a map containing:
- `:z`: The calculated Z-statistic.
- `:stat`: Alias for `:z`.
- `:p-value`: The p-value associated with the Z-statistic and the specified `:sides`.
- `:confidence-interval`: Confidence interval for the true difference in means.
- `:estimate`: The observed difference between sample means (`mean(xs) - mean(ys)`).
- `:n`: Sample sizes as `[count xs, count ys]`.
- `:nx`: Sample size of `xs`.
- `:ny`: Sample size of `ys`.
- `:estimated-mu`: The observed sample means as `[mean xs, mean ys]`.
- `:mu`: The hypothesized difference under the null hypothesis.
- `:stderr`: The standard error of the difference between the means.
- `:alpha`: Significance level used.
- `:sides`: Alternative hypothesis side used.
- `:test-type`: Alias for `:sides`.
- `:paired?`: Boolean indicating if a paired test was performed.
- `:equal-variances?`: Boolean indicating the assumption used for standard error calculation (if unpaired).
See also [[t-test-two-samples]] for smaller samples or when population variances are unknown.cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |