@numero-uno-jpn/rstats 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.ja.md +36 -20
  3. package/README.md +34 -18
  4. package/THIRD_PARTY_NOTICES.md +25 -5
  5. package/dist/chunks/chunk-6R7YDHA2.js +2 -0
  6. package/dist/chunks/chunk-AFKYWGKN.js +2 -0
  7. package/dist/chunks/chunk-ANYGLFT4.js +2 -0
  8. package/dist/chunks/chunk-BI5RSUZ2.js +2 -0
  9. package/dist/chunks/chunk-J3SNI7KY.js +2 -0
  10. package/dist/chunks/chunk-JCZAB6C5.js +2 -0
  11. package/dist/chunks/chunk-MVG5LUZU.js +2 -0
  12. package/dist/chunks/chunk-PTPPP4TI.js +2 -0
  13. package/dist/chunks/chunk-QNQJA6KZ.js +2 -0
  14. package/dist/chunks/chunk-SXSJXDD3.js +2 -0
  15. package/dist/chunks/chunk-UIOAWLAN.js +2 -0
  16. package/dist/chunks/chunk-XYXHHF5L.js +2 -0
  17. package/dist/chunks/chunk-YKN6OGJL.js +2 -0
  18. package/dist/chunks/chunk-ZW52Z3GY.js +2 -0
  19. package/dist/chunks/chunk-ZYA4ISAT.js +2 -0
  20. package/dist/descriptive/basic.d.ts +73 -0
  21. package/dist/descriptive/basic.js +256 -0
  22. package/dist/descriptive/cov.d.ts +39 -0
  23. package/dist/descriptive/cov.js +105 -0
  24. package/dist/descriptive/hist.d.ts +64 -0
  25. package/dist/descriptive/hist.js +304 -0
  26. package/dist/descriptive/moments.d.ts +63 -0
  27. package/dist/descriptive/moments.js +158 -0
  28. package/dist/descriptive/quantile.d.ts +50 -0
  29. package/dist/descriptive/quantile.js +131 -0
  30. package/dist/descriptive/rank.d.ts +23 -0
  31. package/dist/descriptive/rank.js +72 -0
  32. package/dist/descriptive/table.d.ts +54 -0
  33. package/dist/descriptive/table.js +160 -0
  34. package/dist/descriptive.js +2 -0
  35. package/dist/distributions/arcsine.d.ts +24 -0
  36. package/dist/distributions/arcsine.js +73 -0
  37. package/dist/distributions/invgamma.d.ts +29 -0
  38. package/dist/distributions/invgamma.js +85 -0
  39. package/dist/distributions/kumaraswamy.d.ts +17 -0
  40. package/dist/distributions/kumaraswamy.js +96 -0
  41. package/dist/distributions/laplace.d.ts +23 -0
  42. package/dist/distributions/laplace.js +69 -0
  43. package/dist/distributions/multinomial.d.ts +24 -0
  44. package/dist/distributions/multinomial.js +70 -0
  45. package/dist/distributions/nbeta.js +28 -10
  46. package/dist/distributions/nchisq.js +20 -3
  47. package/dist/distributions/pareto.d.ts +23 -0
  48. package/dist/distributions/pareto.js +76 -0
  49. package/dist/distributions/summary.d.ts +25 -0
  50. package/dist/distributions/summary.js +289 -0
  51. package/dist/distributions/triangular.d.ts +25 -0
  52. package/dist/distributions/triangular.js +87 -0
  53. package/dist/distributions.js +2 -0
  54. package/dist/entries/descriptive.d.ts +7 -0
  55. package/dist/entries/descriptive.js +8 -0
  56. package/dist/entries/distributions.d.ts +42 -0
  57. package/dist/entries/distributions.js +42 -0
  58. package/dist/entries/linalg.d.ts +11 -0
  59. package/dist/entries/linalg.js +11 -0
  60. package/dist/entries/numerics.d.ts +8 -0
  61. package/dist/entries/numerics.js +6 -0
  62. package/dist/entries/special.d.ts +10 -0
  63. package/dist/entries/special.js +10 -0
  64. package/dist/entries/tests.d.ts +21 -0
  65. package/dist/entries/tests.js +20 -0
  66. package/dist/htest/ansariTest.d.ts +30 -0
  67. package/dist/htest/ansariTest.js +253 -0
  68. package/dist/htest/aov.d.ts +85 -0
  69. package/dist/htest/aov.js +178 -0
  70. package/dist/htest/binomTest.d.ts +36 -0
  71. package/dist/htest/binomTest.js +121 -0
  72. package/dist/htest/chisqTest.d.ts +34 -2
  73. package/dist/htest/chisqTest.js +140 -37
  74. package/dist/htest/cor.d.ts +14 -0
  75. package/dist/htest/cor.js +4 -3
  76. package/dist/htest/core/ansari.d.ts +25 -0
  77. package/dist/htest/core/ansari.js +186 -0
  78. package/dist/htest/core/kolmogorov.d.ts +26 -0
  79. package/dist/htest/core/kolmogorov.js +221 -0
  80. package/dist/htest/core/mantelhaen.d.ts +26 -0
  81. package/dist/htest/core/mantelhaen.js +145 -0
  82. package/dist/htest/core/shapiro.d.ts +24 -0
  83. package/dist/htest/core/shapiro.js +142 -0
  84. package/dist/htest/core/simulate.d.ts +2 -0
  85. package/dist/htest/core/simulate.js +16 -0
  86. package/dist/htest/core/smirnov.d.ts +20 -0
  87. package/dist/htest/core/smirnov.js +75 -0
  88. package/dist/htest/fisherTest.d.ts +12 -1
  89. package/dist/htest/fisherTest.js +187 -127
  90. package/dist/htest/groups.d.ts +20 -0
  91. package/dist/htest/groups.js +62 -0
  92. package/dist/htest/ksTest.d.ts +31 -0
  93. package/dist/htest/ksTest.js +106 -0
  94. package/dist/htest/mantelhaenTest.d.ts +26 -0
  95. package/dist/htest/mantelhaenTest.js +196 -0
  96. package/dist/htest/mcnemarTest.d.ts +26 -0
  97. package/dist/htest/mcnemarTest.js +99 -0
  98. package/dist/htest/onewayTest.d.ts +26 -0
  99. package/dist/htest/onewayTest.js +97 -0
  100. package/dist/htest/pairwise.d.ts +64 -0
  101. package/dist/htest/pairwise.js +152 -0
  102. package/dist/htest/poissonTest.d.ts +35 -0
  103. package/dist/htest/poissonTest.js +170 -0
  104. package/dist/htest/propTest.d.ts +37 -0
  105. package/dist/htest/propTest.js +164 -0
  106. package/dist/htest/rankTests.d.ts +52 -0
  107. package/dist/htest/rankTests.js +234 -0
  108. package/dist/htest/types.d.ts +2 -0
  109. package/dist/htest/types.js +6 -0
  110. package/dist/htest/varTest.d.ts +48 -0
  111. package/dist/htest/varTest.js +118 -0
  112. package/dist/htest/wilcoxTest.js +136 -174
  113. package/dist/index.d.ts +6 -50
  114. package/dist/index.js +8 -50
  115. package/dist/integrate/quadpack.d.ts +29 -0
  116. package/dist/integrate/quadpack.js +525 -0
  117. package/dist/internal/seq.d.ts +5 -0
  118. package/dist/internal/seq.js +14 -0
  119. package/dist/internal/uniroot.js +10 -71
  120. package/dist/linalg/lu.d.ts +45 -0
  121. package/dist/linalg/lu.js +88 -0
  122. package/dist/linalg/ops.d.ts +90 -0
  123. package/dist/linalg/ops.js +320 -0
  124. package/dist/linalg.js +2 -0
  125. package/dist/models/lm.d.ts +98 -0
  126. package/dist/models/lm.js +187 -0
  127. package/dist/numerics/deriv.d.ts +37 -0
  128. package/dist/numerics/deriv.js +150 -0
  129. package/dist/numerics/integrate.d.ts +91 -0
  130. package/dist/numerics/integrate.js +264 -0
  131. package/dist/numerics/interp.d.ts +103 -0
  132. package/dist/numerics/interp.js +581 -0
  133. package/dist/numerics/ode.d.ts +23 -0
  134. package/dist/numerics/ode.js +59 -0
  135. package/dist/numerics.js +2 -0
  136. package/dist/optim/localmin.d.ts +16 -0
  137. package/dist/optim/localmin.js +97 -0
  138. package/dist/random/beta.js +1 -1
  139. package/dist/random/binomial.js +1 -1
  140. package/dist/random/continuous.js +1 -1
  141. package/dist/random/extra.d.ts +33 -0
  142. package/dist/random/extra.js +62 -0
  143. package/dist/random/gamma.js +1 -1
  144. package/dist/random/hyper.js +1 -1
  145. package/dist/random/mt.js +0 -1
  146. package/dist/random/poisson.js +0 -1
  147. package/dist/random/r2dtable.d.ts +26 -0
  148. package/dist/random/r2dtable.js +153 -0
  149. package/dist/random/rank.js +1 -1
  150. package/dist/random/rng.js +1 -1
  151. package/dist/random/sample.js +1 -1
  152. package/dist/rstats.js +3 -2
  153. package/dist/special/besselIK.d.ts +38 -0
  154. package/dist/special/besselIK.js +315 -0
  155. package/dist/special/besselJY.d.ts +32 -0
  156. package/dist/special/besselJY.js +508 -0
  157. package/dist/special/besselSeries.d.ts +8 -0
  158. package/dist/special/besselSeries.js +24 -0
  159. package/dist/special/beta.js +22 -5
  160. package/dist/special/choose.d.ts +75 -0
  161. package/dist/special/choose.js +233 -0
  162. package/dist/special/erf.d.ts +28 -2
  163. package/dist/special/erf.js +37 -10
  164. package/dist/special/extra.d.ts +47 -0
  165. package/dist/special/extra.js +220 -0
  166. package/dist/special/igam.d.ts +4 -0
  167. package/dist/special/igam.js +57 -2
  168. package/dist/special/incbet.js +77 -22
  169. package/dist/special/lgammaDiff.d.ts +7 -0
  170. package/dist/special/lgammaDiff.js +16 -3
  171. package/dist/special/log1p.d.ts +53 -0
  172. package/dist/special/log1p.js +93 -0
  173. package/dist/special/psigamma.d.ts +48 -0
  174. package/dist/special/psigamma.js +318 -0
  175. package/dist/special/rCompatible.d.ts +8 -0
  176. package/dist/special/rCompatible.js +1 -0
  177. package/dist/special.js +2 -0
  178. package/dist/tests.js +3 -0
  179. package/package.json +26 -1
@@ -0,0 +1,11 @@
1
+ // Linear algebra (rStats.js/linalg): matrices are arrays of rows
2
+ export { crossprod, tcrossprod, backsolve, forwardsolve } from "../linalg/basic.js";
3
+ export { norm } from "../linalg/norm.js";
4
+ export { chol, chol2inv } from "../linalg/chol.js";
5
+ export { qr, qrQ, qrR, qrX, qrCoef, qrQy, qrQty, qrResid, qrFitted, qrSolve } from "../linalg/qr.js";
6
+ export { solve, det, determinant, rcond } from "../linalg/solve.js";
7
+ export { svd } from "../linalg/svd.js";
8
+ export { kappa, ginv } from "../linalg/kappa.js";
9
+ export { eigen } from "../linalg/eigen.js";
10
+ export { matMul, add, subtract, multiply, divide, outer, t, diag, cbind, rbind, matrix, kronecker, seq, } from "../linalg/ops.js";
11
+ export { lu, prcomp } from "../linalg/lu.js";
@@ -0,0 +1,8 @@
1
+ export { integrate, optimize, uniroot } from "../numerics/integrate.js";
2
+ export type { IntegrateOptions, IntegrateResult, OptimizeOptions, UnirootOptions, UnirootResult } from "../numerics/integrate.js";
3
+ export { approx, barylag, hermiteInterp, spline, splinefun, splinefunH } from "../numerics/interp.js";
4
+ export type { ApproxOptions, SplineMethod, SplineOptions, SplinefunOptions } from "../numerics/interp.js";
5
+ export { ode } from "../numerics/ode.js";
6
+ export type { OdeFunc, OdeOptions } from "../numerics/ode.js";
7
+ export { grad, hessian, jacobian } from "../numerics/deriv.js";
8
+ export type { DerivOptions } from "../numerics/deriv.js";
@@ -0,0 +1,6 @@
1
+ // Numerical methods (rStats.js/numerics): integration, optimisation, root finding, interpolation, ODEs and
2
+ // numerical derivatives
3
+ export { integrate, optimize, uniroot } from "../numerics/integrate.js";
4
+ export { approx, barylag, hermiteInterp, spline, splinefun, splinefunH } from "../numerics/interp.js";
5
+ export { ode } from "../numerics/ode.js";
6
+ export { grad, hessian, jacobian } from "../numerics/deriv.js";
@@ -0,0 +1,10 @@
1
+ export { gamma, lgamma } from "../special/gamma.js";
2
+ export { beta, lbeta } from "../special/beta.js";
3
+ export { choose, lchoose, factorial, lfactorial } from "../special/choose.js";
4
+ export type { RCompatibleOptions } from "../special/rCompatible.js";
5
+ export { digamma, trigamma, psigamma } from "../special/psigamma.js";
6
+ export { besselI, besselK, type BesselOptions } from "../special/besselIK.js";
7
+ export { besselJ, besselY } from "../special/besselJY.js";
8
+ export { erf, erfc } from "../special/erf.js";
9
+ export { gammainc, erfinv, erfcinv, perm, type GammaincResult } from "../special/extra.js";
10
+ export { log1pmx, lgamma1p, log1mexp, log1pexp } from "../special/log1p.js";
@@ -0,0 +1,10 @@
1
+ // Special functions (rStats.js/special): gamma, beta and Bessel functions, erf, ...
2
+ export { gamma, lgamma } from "../special/gamma.js";
3
+ export { beta, lbeta } from "../special/beta.js";
4
+ export { choose, lchoose, factorial, lfactorial } from "../special/choose.js";
5
+ export { digamma, trigamma, psigamma } from "../special/psigamma.js";
6
+ export { besselI, besselK } from "../special/besselIK.js";
7
+ export { besselJ, besselY } from "../special/besselJY.js";
8
+ export { erf, erfc } from "../special/erf.js";
9
+ export { gammainc, erfinv, erfcinv, perm } from "../special/extra.js";
10
+ export { log1pmx, lgamma1p, log1mexp, log1pexp } from "../special/log1p.js";
@@ -0,0 +1,21 @@
1
+ export { tTest, type TTestOptions, type TTestResult } from "../htest/tTest.js";
2
+ export { chisqTest, type ChisqTestOptions, type ChisqTestResult, type ChisqTestFactorsResult, type Factor, } from "../htest/chisqTest.js";
3
+ export { fisherTest, type FisherTestOptions, type FisherTestResult } from "../htest/fisherTest.js";
4
+ export { wilcoxTest, type WilcoxTestOptions, type WilcoxTestResult } from "../htest/wilcoxTest.js";
5
+ export { corTest, type CorMethod, type CorOptions, type CorTestOptions, type CorTestResult } from "../htest/cor.js";
6
+ export { pAdjust, type PAdjustMethod, type PAdjustOptions } from "../htest/pAdjust.js";
7
+ export type { Alternative, Counts, HTest, Sample } from "../htest/types.js";
8
+ export { binomTest, type BinomTestOptions, type BinomTestResult } from "../htest/binomTest.js";
9
+ export { poissonTest, type PoissonTestOptions, type PoissonTestResult } from "../htest/poissonTest.js";
10
+ export { propTest, type PropTestOptions, type PropTestResult } from "../htest/propTest.js";
11
+ export { mcnemarTest, type McnemarTestOptions, type McnemarTestResult } from "../htest/mcnemarTest.js";
12
+ export { varTest, bartlettTest, type VarTestOptions, type VarTestResult, type BartlettTestResult } from "../htest/varTest.js";
13
+ export { kruskalTest, friedmanTest, quadeTest, flignerTest, moodTest, type ChisqStatTestResult, type QuadeTestResult, type MoodTestOptions, } from "../htest/rankTests.js";
14
+ export { onewayTest, shapiroTest, type OnewayTestOptions, type OnewayTestResult } from "../htest/onewayTest.js";
15
+ export { mantelhaenTest, type MantelhaenTestOptions, type MantelhaenTestResult } from "../htest/mantelhaenTest.js";
16
+ export { ansariTest, type AnsariTestOptions } from "../htest/ansariTest.js";
17
+ export { ksTest, type KsTestOptions, type KsTestResult } from "../htest/ksTest.js";
18
+ export { pairwiseTTest, pairwiseWilcoxTest, pairwisePropTest, type PairwiseResult, type PairwiseOptions, type PairwiseTTestOptions, type PairwiseWilcoxTestOptions, type PairwisePropTestOptions, } from "../htest/pairwise.js";
19
+ export { aov, TukeyHSD, zTest, type AovResult, type TukeyHSDOptions, type TukeyHSDResult, type ZTestOptions } from "../htest/aov.js";
20
+ export type { GroupLabel } from "../htest/groups.js";
21
+ export { lm, confint, predict, type LmOptions, type LmResult, type ConfintOptions, type PredictOptions } from "../models/lm.js";
@@ -0,0 +1,20 @@
1
+ // Hypothesis tests (rStats.js/tests): R's htest results as plain objects
2
+ export { tTest } from "../htest/tTest.js";
3
+ export { chisqTest, } from "../htest/chisqTest.js";
4
+ export { fisherTest } from "../htest/fisherTest.js";
5
+ export { wilcoxTest } from "../htest/wilcoxTest.js";
6
+ export { corTest } from "../htest/cor.js";
7
+ export { pAdjust } from "../htest/pAdjust.js";
8
+ export { binomTest } from "../htest/binomTest.js";
9
+ export { poissonTest } from "../htest/poissonTest.js";
10
+ export { propTest } from "../htest/propTest.js";
11
+ export { mcnemarTest } from "../htest/mcnemarTest.js";
12
+ export { varTest, bartlettTest } from "../htest/varTest.js";
13
+ export { kruskalTest, friedmanTest, quadeTest, flignerTest, moodTest, } from "../htest/rankTests.js";
14
+ export { onewayTest, shapiroTest } from "../htest/onewayTest.js";
15
+ export { mantelhaenTest } from "../htest/mantelhaenTest.js";
16
+ export { ansariTest } from "../htest/ansariTest.js";
17
+ export { ksTest } from "../htest/ksTest.js";
18
+ export { pairwiseTTest, pairwiseWilcoxTest, pairwisePropTest, } from "../htest/pairwise.js";
19
+ export { aov, TukeyHSD, zTest } from "../htest/aov.js";
20
+ export { lm, confint, predict } from "../models/lm.js";
@@ -0,0 +1,30 @@
1
+ import { type Alternative, type HTest, type Sample } from "./types.js";
2
+ /** Options for {@link ansariTest}. */
3
+ export interface AnsariTestOptions {
4
+ /** Alternative hypothesis (unambiguous abbreviations accepted). Default `"two.sided"`. */
5
+ alternative?: Alternative | "two" | "l" | "g";
6
+ /** Exact p-value. Default: exact when both samples have fewer than 50 values and there are no ties. */
7
+ exact?: boolean;
8
+ /** Compute a confidence interval for the ratio of scales and its estimate (R's `conf.int`). Default `false`. */
9
+ confInt?: boolean;
10
+ /** Confidence level of the interval. Default `0.95`. */
11
+ confLevel?: number;
12
+ }
13
+ /**
14
+ * Ansari-Bradley test that two samples differ in scale. Equivalent to R's `ansari.test()`.
15
+ * `NaN` values are dropped.
16
+ *
17
+ * With `confInt: true`, `confInt` is the interval for the ratio of the scales of `x` and `y` and `estimate` its
18
+ * estimate, both computed with the locations taken as 0 (exact without ties when both samples have fewer than 50
19
+ * values, otherwise by the normal approximation, whose limits are roots found to a tolerance of 1e-4 as in R). Limits
20
+ * that cannot be formed (the samples differ in location) are `NaN`. With ties and `exact` unset or `true`, R fails
21
+ * ("object 'cint' not found"); rStats.js returns the normal-approximation interval, as with `exact: false`.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const r = ansariTest([-2, -1, 1, 2], [-4, -3, 3, 4], { confInt: true });
26
+ * r.confInt; // [0.25, 0.6666666666666666]
27
+ * r.estimate; // 0.41666666666666663
28
+ * ```
29
+ */
30
+ export declare function ansariTest(x: Sample, y: Sample, options?: AnsariTestOptions): HTest;
@@ -0,0 +1,253 @@
1
+ // Ansari-Bradley two-sample test of scale (R's ansari.test), with the confidence interval for the ratio of scales.
2
+ //
3
+ // Written for rStats.js from the published test (Ansari and Bradley, Ann. Math. Stat. 31, 1960; no ported code).
4
+ // Scores min(r, N + 1 - r) of the pooled ranks r (average ranks for ties); the statistic is the sum over the first
5
+ // sample. Small samples without ties use the exact null distribution (src/htest/core/ansari.ts); the two-sided
6
+ // p-value doubles the tail on the statistic's side of the centre floor((m+1)^2/4) + floor(m n / 2)/2 (the centre
7
+ // follows R's ansari.test behaviour). Otherwise the statistic is standardised and compared with the normal, with Ansari
8
+ // and Bradley's mean and the variance of a linear rank statistic from the observed sum of squared scores (the form
9
+ // scipy.stats.ansari also uses).
10
+ //
11
+ // Interval and estimate (Bauer, JASA 67, 1972, section 5): with the locations taken as 0, AB(s) is the statistic of
12
+ // x / s against y, a step function of the ratio of scales s. Exact: AB(s) is evaluated between consecutive
13
+ // candidate ratios x_i / y_j >= 0 (and beyond the largest), and the limits are the candidate ratios where it crosses
14
+ // the exact quantiles; the estimate is the midpoint of the crossing of the median. Normal approximation: the limits and
15
+ // the estimate are where the standardised AB(s) (standardised as for the test: R 4.5.2's ansari.test) crosses the normal
16
+ // quantiles (and 0), found with R's uniroot conventions (tolerance 1e-4) in the range of the ratios of the positive
17
+ // values and of the negative values. The candidate sets, evaluation points, search range, tolerance and the cases
18
+ // returned as NaN (R's NA) follow R's documented and observed behaviour.
19
+ import { pnorm, qnorm } from "../distributions/normal.js";
20
+ import { rank } from "../internal/summary.js";
21
+ import { uniroot } from "../internal/uniroot.js";
22
+ import { pansariExact, qansariR } from "./core/ansari.js";
23
+ import { checkConfLevelOpen, matchAlternative } from "./types.js";
24
+ /**
25
+ * Ansari-Bradley test that two samples differ in scale. Equivalent to R's `ansari.test()`.
26
+ * `NaN` values are dropped.
27
+ *
28
+ * With `confInt: true`, `confInt` is the interval for the ratio of the scales of `x` and `y` and `estimate` its
29
+ * estimate, both computed with the locations taken as 0 (exact without ties when both samples have fewer than 50
30
+ * values, otherwise by the normal approximation, whose limits are roots found to a tolerance of 1e-4 as in R). Limits
31
+ * that cannot be formed (the samples differ in location) are `NaN`. With ties and `exact` unset or `true`, R fails
32
+ * ("object 'cint' not found"); rStats.js returns the normal-approximation interval, as with `exact: false`.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const r = ansariTest([-2, -1, 1, 2], [-4, -3, 3, 4], { confInt: true });
37
+ * r.confInt; // [0.25, 0.6666666666666666]
38
+ * r.estimate; // 0.41666666666666663
39
+ * ```
40
+ */
41
+ export function ansariTest(x, y, options = {}) {
42
+ const xs = Array.from(x).filter((v) => !Number.isNaN(v));
43
+ const ys = Array.from(y).filter((v) => !Number.isNaN(v));
44
+ const m = xs.length;
45
+ const n = ys.length;
46
+ if (m < 1)
47
+ throw new RangeError("not enough 'x' observations");
48
+ if (n < 1)
49
+ throw new RangeError("not enough 'y' observations");
50
+ const alternative = matchAlternative(options.alternative);
51
+ const confInt = options.confInt ?? false;
52
+ const confLevel = options.confLevel ?? 0.95;
53
+ if (confInt)
54
+ checkConfLevelOpen(confLevel);
55
+ const N = m + n;
56
+ const r = rank(xs.concat(ys));
57
+ const a = r.map((v) => Math.min(v, N - v + 1));
58
+ let statistic = 0;
59
+ for (let i = 0; i < m; i++)
60
+ statistic += a[i];
61
+ const ties = new Set(r).size < N;
62
+ const exact = options.exact ?? (m < 50 && n < 50 && !ties);
63
+ let pValue;
64
+ let ci;
65
+ if (exact && !ties) {
66
+ const upperFrom = (q) => pansariExact(q - 1, m, n, false); // P(AB >= q)
67
+ const lowerTo = (q) => pansariExact(q, m, n, true); // P(AB <= q)
68
+ if (alternative === "two.sided") {
69
+ // the smaller tail, judged by the position of the statistic against the centre of the distribution (the centre
70
+ // follows R's ansari.test behaviour)
71
+ const centre = Math.floor((m + 1) ** 2 / 4) + Math.floor((m * n) / 2) / 2;
72
+ pValue = Math.min(1, 2 * (statistic > centre ? upperFrom(statistic) : lowerTo(statistic)));
73
+ }
74
+ else if (alternative === "less")
75
+ pValue = upperFrom(statistic);
76
+ else
77
+ pValue = lowerTo(statistic);
78
+ if (confInt)
79
+ ci = exactInterval(xs, ys, alternative, confLevel);
80
+ }
81
+ else {
82
+ // mean and variance with the sum of the scores at its value without ties (N (N + 2) / 4 for even N,
83
+ // (N + 1)^2 / 4 for odd N), and the sum of their squares as observed
84
+ let sq = 0;
85
+ for (const v of a)
86
+ sq += v * v;
87
+ const even = N % 2 === 0;
88
+ const mean = even ? (m * (N + 2)) / 4 : (m * (N + 1) ** 2) / (4 * N);
89
+ const variance = even
90
+ ? (m * n * (16 * sq - N * (N + 2) ** 2)) / (16 * N * (N - 1))
91
+ : (m * n * (16 * N * sq - (N + 1) ** 4)) / (16 * N * N * (N - 1));
92
+ const z = (statistic - mean) / Math.sqrt(variance);
93
+ // large AB means the first sample is concentrated in the middle: smaller scale
94
+ pValue =
95
+ alternative === "two.sided"
96
+ ? 2 * Math.min(pnorm(z), pnorm(z, { lowerTail: false }))
97
+ : alternative === "less"
98
+ ? pnorm(z, { lowerTail: false })
99
+ : pnorm(z);
100
+ if (confInt)
101
+ ci = normalInterval(xs, ys, alternative, confLevel);
102
+ }
103
+ const result = {
104
+ method: "Ansari-Bradley test",
105
+ alternative,
106
+ statistic,
107
+ statisticName: "AB",
108
+ pValue,
109
+ };
110
+ if (ci !== undefined) {
111
+ result.confInt = ci.confInt;
112
+ result.confLevel = confLevel;
113
+ result.estimate = ci.estimate;
114
+ result.estimateNames = "ratio of scales";
115
+ }
116
+ result.nullValue = 1;
117
+ result.nullValueName = "ratio of scales";
118
+ return result;
119
+ }
120
+ /** AB statistic of x / s against y, with the scores of all observations and whether there are ties */
121
+ function scaledStatistic(xs, ys, s) {
122
+ const m = xs.length;
123
+ const N = m + ys.length;
124
+ const r = rankNaNLast(xs.map((v) => v / s).concat(ys));
125
+ const a = r.map((v) => Math.min(v, N - v + 1));
126
+ let ab = 0;
127
+ for (let i = 0; i < m; i++)
128
+ ab += a[i];
129
+ return { ab, a, ties: new Set(r).size < N };
130
+ }
131
+ /** Average ranks with NaN (0 / 0 at s = 0) ranked last in order of appearance, as R's rank(na.last = TRUE) */
132
+ function rankNaNLast(v) {
133
+ const keep = v.filter((e) => !Number.isNaN(e));
134
+ if (keep.length === v.length)
135
+ return rank(v);
136
+ const rk = rank(keep);
137
+ let i = 0;
138
+ let next = keep.length;
139
+ return v.map((e) => (Number.isNaN(e) ? ++next : rk[i++]));
140
+ }
141
+ /** One-sided limits at level 1 - 2a for "greater" (lower limit) and "less" (upper limit), two-sided otherwise */
142
+ function shapeInterval(alternative, a, limits) {
143
+ if (alternative === "two.sided")
144
+ return limits(a);
145
+ if (alternative === "greater")
146
+ return [limits(2 * a)[0], Infinity];
147
+ return [0, limits(2 * a)[1]];
148
+ }
149
+ /** Exact interval and estimate from the candidate ratios x_i / y_j >= 0 */
150
+ function exactInterval(xs, ys, alternative, confLevel) {
151
+ const m = xs.length;
152
+ const n = ys.length;
153
+ const sigma = [];
154
+ for (const x of xs)
155
+ for (const y of ys)
156
+ if (x / y >= 0)
157
+ sigma.push(x / y);
158
+ sigma.sort((p, q) => p - q);
159
+ const L = sigma.length;
160
+ if (L === 0)
161
+ return { confInt: shapeInterval(alternative, 1 - confLevel, () => [NaN, NaN]), estimate: NaN };
162
+ // AB between consecutive candidates, and at 2.01 times the largest
163
+ const abs = sigma.map((v, k) => scaledStatistic(xs, ys, v + (k < L - 1 ? (sigma[k + 1] - v) / 2 : v * 1.01)).ab);
164
+ // the largest candidate with the smallest positive AB - q (or the smallest with the smallest AB - q >= 0)
165
+ const crossing = (q, strict, largest) => {
166
+ let best = Infinity;
167
+ for (const v of abs)
168
+ if ((strict ? v - q > 0 : v - q >= 0) && v - q < best)
169
+ best = v - q;
170
+ let out = largest ? -Infinity : Infinity;
171
+ abs.forEach((v, k) => {
172
+ if (v - q === best)
173
+ out = largest ? Math.max(out, sigma[k]) : Math.min(out, sigma[k]);
174
+ });
175
+ return out;
176
+ };
177
+ const limits = (alpha) => {
178
+ const qLow = qansariR(alpha / 2, m, n);
179
+ const qHigh = qansariR(1 - alpha / 2, m, n);
180
+ if (!abs.some((v) => v - qLow >= 0) || !abs.some((v) => v - qHigh > 0))
181
+ return [NaN, NaN];
182
+ const lower = crossing(qLow, false, false);
183
+ const upper = crossing(qHigh, true, true);
184
+ // AB need not be monotone in s: if the limits come out in the wrong order, the quantiles are interchanged
185
+ if (lower > upper)
186
+ return [crossing(qHigh, false, false), crossing(qLow, true, true)];
187
+ return [lower, upper];
188
+ };
189
+ const confInt = shapeInterval(alternative, 1 - confLevel, limits);
190
+ const qMed = qansariR(0.5, m, n);
191
+ let below = -Infinity;
192
+ let above = Infinity;
193
+ abs.forEach((v, k) => {
194
+ if (v - qMed <= 0)
195
+ below = Math.max(below, sigma[k]);
196
+ else
197
+ above = Math.min(above, sigma[k]);
198
+ });
199
+ const estimate = below === -Infinity || above === Infinity ? NaN : (above + below) / 2;
200
+ return { confInt, estimate };
201
+ }
202
+ /** Normal-approximation interval and estimate (undefined when the search range is not finite) */
203
+ function normalInterval(xs, ys, alternative, confLevel) {
204
+ const m = xs.length;
205
+ const n = ys.length;
206
+ const N = m + n;
207
+ const even = N % 2 === 0;
208
+ const z = (s, zq) => {
209
+ const { ab, a, ties } = scaledStatistic(xs, ys, s);
210
+ const centred = even ? ab - (m * (N + 2)) / 4 : ab - (m * (N + 1) ** 2) / (4 * N);
211
+ let sd;
212
+ if (!ties) {
213
+ sd = even
214
+ ? Math.sqrt((m * n * (N + 2) * (N - 2)) / (48 * (N - 1)))
215
+ : Math.sqrt((m * n * (N + 1) * (3 + N * N)) / (48 * N * N));
216
+ }
217
+ else {
218
+ let sq = 0;
219
+ for (const v of a)
220
+ sq += v * v;
221
+ sd = even
222
+ ? Math.sqrt((m * n * (16 * sq - N * (N + 2) ** 2)) / (16 * N * (N - 1)))
223
+ : Math.sqrt((m * n * (16 * N * sq - (N + 1) ** 4)) / (16 * N * N * (N - 1)));
224
+ }
225
+ return centred / sd - zq;
226
+ };
227
+ // search range: the ratios of the positive values, and of the non-positive x to the negative y
228
+ const ends = [];
229
+ const range = (xp, yp) => {
230
+ if (xp.length === 0 || yp.length === 0)
231
+ return;
232
+ ends.push(Math.min(...xp) / Math.max(...yp), Math.max(...xp) / Math.min(...yp));
233
+ };
234
+ range(xs.filter((v) => v > 0), ys.filter((v) => v > 0));
235
+ range(xs.filter((v) => v <= 0), ys.filter((v) => v < 0));
236
+ if (ends.some((v) => !Number.isFinite(v)))
237
+ return undefined;
238
+ const lo = Math.min(...ends);
239
+ const hi = Math.max(...ends);
240
+ const root = (zq) => uniroot((s) => z(s, zq), lo, hi, { tol: 1e-4 });
241
+ const limits = (alpha) => {
242
+ const zLow = qnorm(alpha / 2);
243
+ const zHigh = qnorm(alpha / 2, { lowerTail: false });
244
+ if (z(lo, zLow) > 0 || z(hi, zHigh) < 0)
245
+ return [NaN, NaN];
246
+ const u = root(zLow);
247
+ const l = root(zHigh);
248
+ return u <= l ? [u, l] : [l, u];
249
+ };
250
+ const confInt = shapeInterval(alternative, 1 - confLevel, limits);
251
+ const estimate = z(lo, 0) > 0 || z(hi, 0) < 0 ? NaN : root(0);
252
+ return { confInt, estimate };
253
+ }
@@ -0,0 +1,85 @@
1
+ import { type GroupLabel } from "./groups.js";
2
+ import { type Alternative, type HTest, type Sample } from "./types.js";
3
+ /** Result of {@link aov}: the one-way ANOVA table, rows "between groups" and "residuals". */
4
+ export interface AovResult {
5
+ /** Degrees of freedom `[k - 1, N - k]`. */
6
+ df: [number, number];
7
+ /** Sums of squares `[between, residual]`. */
8
+ sumSq: [number, number];
9
+ /** Mean squares `[between, residual]`. */
10
+ meanSq: [number, number];
11
+ /** F statistic. */
12
+ fValue: number;
13
+ /** p-value of the F test. */
14
+ pValue: number;
15
+ }
16
+ /**
17
+ * One-way analysis of variance. Equivalent to the table of R's `summary(aov(y ~ g))` for one factor.
18
+ *
19
+ * @param x An array of samples (groups), or one sample with group labels `g`.
20
+ * @param g Group labels, parallel to `x`.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const r = aov([[2.9, 3.0, 2.5, 2.6, 3.2], [3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]);
25
+ * r.fValue; // 0.5600732600732597
26
+ * r.pValue; // 0.586632991041738
27
+ * ```
28
+ */
29
+ export declare function aov(x: Sample | readonly Sample[], g?: readonly GroupLabel[]): AovResult;
30
+ /** Options for {@link TukeyHSD}. */
31
+ export interface TukeyHSDOptions {
32
+ /** Family-wise confidence level. Default `0.95`. */
33
+ confLevel?: number;
34
+ }
35
+ /** Result of {@link TukeyHSD}: one entry per pair of groups, in R's order (2-1, 3-1, ..., k-1, 3-2, ...). */
36
+ export interface TukeyHSDResult {
37
+ /**
38
+ * Labels of the comparisons, `"a-b"`: the group labels when given, otherwise the positions of the samples in the
39
+ * list (from 1). Groups without data are left out, as in R.
40
+ */
41
+ names: string[];
42
+ /** The group compared (1-based position among the groups compared, i > j). */
43
+ i: number[];
44
+ /** The group it is compared with (1-based index). */
45
+ j: number[];
46
+ /** Difference of means, group i minus group j. */
47
+ diff: number[];
48
+ /** Lower ends of the simultaneous intervals. */
49
+ lwr: number[];
50
+ /** Upper ends. */
51
+ upr: number[];
52
+ /** p-values adjusted for the multiple comparisons. */
53
+ pAdj: number[];
54
+ }
55
+ /**
56
+ * Tukey's honest significant differences between the group means of a one-way ANOVA (Tukey-Kramer for unequal
57
+ * sizes). Equivalent to R's `TukeyHSD(aov(y ~ g))`.
58
+ *
59
+ * @param x An array of samples (groups), or one sample with group labels `g` (then `options` comes third).
60
+ */
61
+ export declare function TukeyHSD(x: Sample | readonly Sample[], g?: readonly GroupLabel[] | TukeyHSDOptions, options?: TukeyHSDOptions): TukeyHSDResult;
62
+ /** Options for {@link zTest}. */
63
+ export interface ZTestOptions {
64
+ /** Known standard deviation of the population of `x` (required). */
65
+ sigmaX?: number;
66
+ /** Known standard deviation of the population of `y` (required with `y`). */
67
+ sigmaY?: number;
68
+ /** Mean (or difference of means) under the null hypothesis. Default `0`. */
69
+ mu?: number;
70
+ /** Alternative hypothesis (unambiguous abbreviations accepted). Default `"two.sided"`. */
71
+ alternative?: Alternative | "two" | "l" | "g";
72
+ /** Confidence level of the interval. Default `0.95`. */
73
+ confLevel?: number;
74
+ }
75
+ /**
76
+ * z test for the mean of one sample, or the difference of the means of two, with known standard deviations.
77
+ * Equivalent to `BSDA::z.test()` (the open end of a one-sided interval is ±Infinity here, NA in BSDA). `NaN` values
78
+ * are dropped.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * zTest([5.1, 4.9, 5.6, 5.8, 6.0], { mu: 5, sigmaX: 0.5 }).pValue;
83
+ * ```
84
+ */
85
+ export declare function zTest(x: Sample, y?: Sample | ZTestOptions, options?: ZTestOptions): HTest;
@@ -0,0 +1,178 @@
1
+ // One-way analysis of variance (the table of R's summary(aov(y ~ g))), Tukey's honest significant differences (R's
2
+ // TukeyHSD) and the z test with known standard deviations (as BSDA's z.test).
3
+ //
4
+ // Written for rStats.js from the textbook formulas. The sums of squares are accumulated in
5
+ // double-double: between groups sum n_i (m_i - m)^2, within groups sum (x - m_i)^2, so a within sum that is exactly
6
+ // 0 stays 0 (F = Inf; R's QR leaves rounding residue there). TukeyHSD uses the Tukey-Kramer standard error
7
+ // sqrt(MSE / 2 (1/n_i + 1/n_j)) with the studentized range distribution for the interval and the adjusted p-value.
8
+ // zTest is the textbook z test (standard error sigma / sqrt(n), or sqrt(sigma_x^2/n_x + sigma_y^2/n_y) for two
9
+ // samples, normal quantiles for the interval around the estimate); its input checks (at least 3 observations,
10
+ // confLevel allowed in the closed [0, 1]) follow BSDA's documented/observed behaviour, with messages of our own.
11
+ import { pf1 } from "../distributions/f.js";
12
+ import { pnorm, qnorm } from "../distributions/normal.js";
13
+ import { ptukey, qtukey } from "../distributions/tukey.js";
14
+ import { meanDD } from "../internal/summary.js";
15
+ import { ddAdd, ddMul, ddSub } from "../special/dd.js";
16
+ import { labelledGroups, toGroups } from "./groups.js";
17
+ import { matchAlternative } from "./types.js";
18
+ function sums(groups) {
19
+ const all = groups.flat();
20
+ const m = meanDD(all);
21
+ let ssb = [0, 0];
22
+ let ssw = [0, 0];
23
+ const means = [];
24
+ for (const g of groups) {
25
+ const mi = meanDD(g);
26
+ means.push(mi[0]);
27
+ const d = ddSub(mi, m);
28
+ ssb = ddAdd(ssb, ddMul(ddMul(d, d), [g.length, 0]));
29
+ for (const v of g) {
30
+ const e = ddSub([v, 0], mi);
31
+ ssw = ddAdd(ssw, ddMul(e, e));
32
+ }
33
+ }
34
+ return { ssb: ssb[0], ssw: ssw[0], means };
35
+ }
36
+ /**
37
+ * One-way analysis of variance. Equivalent to the table of R's `summary(aov(y ~ g))` for one factor.
38
+ *
39
+ * @param x An array of samples (groups), or one sample with group labels `g`.
40
+ * @param g Group labels, parallel to `x`.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const r = aov([[2.9, 3.0, 2.5, 2.6, 3.2], [3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]);
45
+ * r.fValue; // 0.5600732600732597
46
+ * r.pValue; // 0.586632991041738
47
+ * ```
48
+ */
49
+ export function aov(x, g) {
50
+ const groups = toGroups(x, g);
51
+ const k = groups.length;
52
+ if (k < 2)
53
+ throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
54
+ const N = groups.reduce((a, s) => a + s.length, 0);
55
+ const { ssb, ssw } = sums(groups);
56
+ const df1 = k - 1;
57
+ const df2 = N - k;
58
+ const msb = ssb / df1;
59
+ const msw = ssw / df2;
60
+ const fValue = msb / msw;
61
+ return {
62
+ df: [df1, df2],
63
+ sumSq: [ssb, ssw],
64
+ meanSq: [msb, msw],
65
+ fValue,
66
+ pValue: df2 > 0 ? pf1(fValue, df1, df2, false, false) : NaN,
67
+ };
68
+ }
69
+ /**
70
+ * Tukey's honest significant differences between the group means of a one-way ANOVA (Tukey-Kramer for unequal
71
+ * sizes). Equivalent to R's `TukeyHSD(aov(y ~ g))`.
72
+ *
73
+ * @param x An array of samples (groups), or one sample with group labels `g` (then `options` comes third).
74
+ */
75
+ export function TukeyHSD(x, g, options = {}) {
76
+ let labels;
77
+ if (g !== undefined && !Array.isArray(g))
78
+ options = g;
79
+ else
80
+ labels = g;
81
+ // names follow the groups: a label (or list position) whose values are all missing has no group, as R drops the
82
+ // unused factor level
83
+ const { labels: names, groups } = labelledGroups(x, labels);
84
+ const k = groups.length;
85
+ if (k < 2)
86
+ throw new RangeError("contrasts can be applied only to factors with 2 or more levels");
87
+ const confLevel = options.confLevel ?? 0.95;
88
+ const N = groups.reduce((a, s) => a + s.length, 0);
89
+ const df = N - k;
90
+ const { ssw, means } = sums(groups);
91
+ const mse = ssw / df;
92
+ const q = qtukey(confLevel, k, df);
93
+ const out = { names: [], i: [], j: [], diff: [], lwr: [], upr: [], pAdj: [] };
94
+ for (let b = 0; b < k - 1; b++) {
95
+ for (let a = b + 1; a < k; a++) {
96
+ const diff = means[a] - means[b];
97
+ const se = Math.sqrt((mse / 2) * (1 / groups[a].length + 1 / groups[b].length));
98
+ out.names.push(`${names[a]}-${names[b]}`);
99
+ out.i.push(a + 1);
100
+ out.j.push(b + 1);
101
+ out.diff.push(diff);
102
+ out.lwr.push(diff - q * se);
103
+ out.upr.push(diff + q * se);
104
+ out.pAdj.push(ptukey(Math.abs(diff) / se, k, df, { lowerTail: false }));
105
+ }
106
+ }
107
+ return out;
108
+ }
109
+ /**
110
+ * z test for the mean of one sample, or the difference of the means of two, with known standard deviations.
111
+ * Equivalent to `BSDA::z.test()` (the open end of a one-sided interval is ±Infinity here, NA in BSDA). `NaN` values
112
+ * are dropped.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * zTest([5.1, 4.9, 5.6, 5.8, 6.0], { mu: 5, sigmaX: 0.5 }).pValue;
117
+ * ```
118
+ */
119
+ export function zTest(x, y, options = {}) {
120
+ let ys;
121
+ if (y !== undefined && !ArrayBuffer.isView(y) && !Array.isArray(y))
122
+ options = y;
123
+ else
124
+ ys = y;
125
+ const { sigmaX, sigmaY } = options;
126
+ const mu = options.mu ?? 0;
127
+ if (sigmaX === undefined && ys === undefined)
128
+ throw new RangeError("sigmaX (the known standard deviation of x) is required");
129
+ if (sigmaX === undefined || (ys !== undefined && sigmaY === undefined)) {
130
+ throw new RangeError("sigmaX and sigmaY are both required for two samples");
131
+ }
132
+ if (Number.isNaN(mu))
133
+ throw new RangeError("mu must be a number");
134
+ const alternative = matchAlternative(options.alternative);
135
+ const confLevel = options.confLevel ?? 0.95;
136
+ if (!(confLevel >= 0 && confLevel <= 1))
137
+ throw new RangeError("confLevel must be between 0 and 1");
138
+ const xs = Array.from(x).filter((v) => !Number.isNaN(v));
139
+ const yv = ys === undefined ? undefined : Array.from(ys).filter((v) => !Number.isNaN(v));
140
+ if (xs.length < 3)
141
+ throw new RangeError("x needs at least 3 non-missing values");
142
+ if (yv !== undefined && yv.length < 3)
143
+ throw new RangeError("y needs at least 3 non-missing values");
144
+ const meanX = meanDD(xs)[0];
145
+ const meanY = yv === undefined ? NaN : meanDD(yv)[0];
146
+ const se = yv === undefined ? sigmaX / Math.sqrt(xs.length) : Math.sqrt(sigmaX ** 2 / xs.length + sigmaY ** 2 / yv.length);
147
+ const target = yv === undefined ? meanX : meanX - meanY;
148
+ const z = (target - mu) / se;
149
+ let pValue;
150
+ let confInt;
151
+ if (alternative === "less") {
152
+ pValue = pnorm(z);
153
+ confInt = [-Infinity, target + qnorm(confLevel) * se];
154
+ }
155
+ else if (alternative === "greater") {
156
+ pValue = pnorm(z, { lowerTail: false });
157
+ confInt = [target - qnorm(confLevel) * se, Infinity];
158
+ }
159
+ else {
160
+ pValue = 2 * pnorm(-Math.abs(z));
161
+ const half = qnorm(1 - (1 - confLevel) / 2) * se;
162
+ confInt = [target - half, target + half];
163
+ }
164
+ const twoSample = yv !== undefined;
165
+ return {
166
+ method: twoSample ? "Two-sample z-Test" : "One-sample z-Test",
167
+ alternative,
168
+ statistic: z,
169
+ statisticName: "z",
170
+ pValue,
171
+ confInt,
172
+ confLevel,
173
+ estimate: twoSample ? [meanX, meanY] : meanX,
174
+ estimateNames: twoSample ? ["mean of x", "mean of y"] : "mean of x",
175
+ nullValue: mu,
176
+ nullValueName: twoSample ? "difference in means" : "mean",
177
+ };
178
+ }