@numero-uno-jpn/rstats 0.15.3 → 0.17.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.
- package/CHANGELOG.md +294 -0
- package/README.ja.md +68 -35
- package/README.md +65 -30
- package/dist/chunks/chunk-2C33MXSW.js +3 -0
- package/dist/chunks/chunk-34S5SQY6.js +2 -0
- package/dist/chunks/chunk-4WE3OO62.js +2 -0
- package/dist/chunks/chunk-5AYHCITP.js +2 -0
- package/dist/chunks/chunk-6JJQL6HL.js +2 -0
- package/dist/chunks/chunk-C7V2FH6L.js +3 -0
- package/dist/chunks/chunk-CZI7KUO3.js +2 -0
- package/dist/chunks/chunk-DXI5N2ET.js +2 -0
- package/dist/chunks/chunk-FY3FVOBM.js +2 -0
- package/dist/chunks/chunk-H3WVPZDL.js +2 -0
- package/dist/chunks/chunk-LHUIJQHY.js +2 -0
- package/dist/chunks/chunk-LV3W2F7N.js +2 -0
- package/dist/chunks/chunk-M4ITG7YR.js +2 -0
- package/dist/chunks/chunk-NSYZTS26.js +2 -0
- package/dist/chunks/chunk-ONY5CISH.js +2 -0
- package/dist/chunks/chunk-RFE7MVP7.js +2 -0
- package/dist/chunks/chunk-SE7V2KLO.js +2 -0
- package/dist/chunks/chunk-THIGHOKK.js +2 -0
- package/dist/chunks/chunk-TNMJPQPV.js +2 -0
- package/dist/chunks/chunk-WM7VFXTV.js +2 -0
- package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
- package/dist/chunks/chunk-XLSFJTTK.js +2 -0
- package/dist/chunks/chunk-Z37NELOS.js +2 -0
- package/dist/chunks/chunk-ZFQWB222.js +2 -0
- package/dist/data/grouping.js +26 -7
- package/dist/descriptive/basic.js +110 -8
- package/dist/descriptive/cov.js +23 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +69 -23
- package/dist/descriptive/factanal.d.ts +2 -0
- package/dist/descriptive/factanal.js +26 -9
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +77 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +86 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +74 -10
- package/dist/descriptive/pivot.d.ts +25 -10
- package/dist/descriptive/pivot.js +182 -42
- package/dist/descriptive/quantile.js +10 -1
- package/dist/descriptive/rank.js +8 -1
- package/dist/descriptive/table.d.ts +23 -3
- package/dist/descriptive/table.js +36 -21
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +27 -2
- package/dist/distributions/beta.js +33 -4
- package/dist/distributions/binomial.js +46 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +21 -4
- package/dist/distributions/chisq.js +16 -3
- package/dist/distributions/exponential.js +14 -0
- package/dist/distributions/f.js +41 -17
- package/dist/distributions/gamma.js +35 -3
- package/dist/distributions/geometric.js +58 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +101 -6
- package/dist/distributions/invgamma.js +10 -1
- package/dist/distributions/kumaraswamy.js +9 -0
- package/dist/distributions/laplace.js +36 -6
- package/dist/distributions/logistic.js +13 -1
- package/dist/distributions/lognormal.js +16 -2
- package/dist/distributions/multinomial.js +58 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +102 -17
- package/dist/distributions/normal.js +17 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +12 -1
- package/dist/distributions/poisson.js +37 -3
- package/dist/distributions/signrank.js +16 -4
- package/dist/distributions/summary.d.ts +2 -1
- package/dist/distributions/summary.js +481 -61
- package/dist/distributions/t.js +9 -0
- package/dist/distributions/triangular.js +19 -5
- package/dist/distributions/tukey.js +11 -2
- package/dist/distributions/uniform.js +8 -0
- package/dist/distributions/weibull.js +18 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +164 -26
- package/dist/distributions.js +2 -2
- package/dist/entries/descriptive.d.ts +3 -1
- package/dist/entries/descriptive.js +1 -1
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +2 -0
- package/dist/entries/linalg.d.ts +3 -1
- package/dist/entries/mixed.d.ts +3 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/numerics.d.ts +2 -1
- package/dist/entries/tests.d.ts +8 -5
- package/dist/entries/tests.js +3 -1
- package/dist/htest/agreement.d.ts +16 -2
- package/dist/htest/agreement.js +122 -21
- package/dist/htest/ansariTest.d.ts +8 -2
- package/dist/htest/ansariTest.js +116 -18
- package/dist/htest/aov.d.ts +29 -23
- package/dist/htest/aov.js +90 -47
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +47 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +12 -5
- package/dist/htest/chisqTest.d.ts +5 -2
- package/dist/htest/chisqTest.js +151 -46
- package/dist/htest/cor.d.ts +9 -2
- package/dist/htest/cor.js +57 -26
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/core/simulate.d.ts +6 -0
- package/dist/htest/core/simulate.js +20 -0
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +5 -0
- package/dist/htest/effectSize.js +117 -35
- package/dist/htest/fisherTest.d.ts +4 -3
- package/dist/htest/fisherTest.js +88 -24
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +7 -1
- package/dist/htest/ksTest.js +36 -6
- package/dist/htest/leveneTest.d.ts +2 -0
- package/dist/htest/leveneTest.js +28 -6
- package/dist/htest/mantelhaenTest.js +132 -25
- package/dist/htest/mcnemarTest.js +40 -11
- package/dist/htest/multipleComparisons.d.ts +24 -26
- package/dist/htest/multipleComparisons.js +70 -64
- package/dist/htest/normalityTests.js +54 -14
- package/dist/htest/onewayTest.js +106 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +42 -6
- package/dist/htest/pairwise.d.ts +3 -1
- package/dist/htest/pairwise.js +46 -21
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +117 -59
- package/dist/htest/polycor.js +47 -17
- package/dist/htest/power.d.ts +15 -1
- package/dist/htest/power.js +128 -10
- package/dist/htest/propTest.d.ts +3 -0
- package/dist/htest/propTest.js +44 -6
- package/dist/htest/pwr.d.ts +38 -1
- package/dist/htest/pwr.js +159 -39
- package/dist/htest/rankTests.js +36 -6
- package/dist/htest/tTest.d.ts +2 -0
- package/dist/htest/tTest.js +53 -21
- package/dist/htest/testFormula.js +11 -11
- package/dist/htest/trendTests.d.ts +28 -4
- package/dist/htest/trendTests.js +124 -35
- package/dist/htest/types.d.ts +7 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +52 -14
- package/dist/htest/wilcoxTest.js +164 -29
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/checkOptions.d.ts +11 -0
- package/dist/internal/checkOptions.js +31 -0
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +15 -1
- package/dist/internal/ddexp.js +59 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.js +15 -2
- package/dist/internal/optionalArgs.d.ts +12 -0
- package/dist/internal/optionalArgs.js +46 -0
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/internal/warnings.d.ts +66 -0
- package/dist/internal/warnings.js +122 -0
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +58 -7
- package/dist/linalg/chol.js +10 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +75 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +113 -15
- package/dist/linalg/kappa.js +64 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +40 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/norm.js +4 -0
- package/dist/linalg/ops.d.ts +27 -2
- package/dist/linalg/ops.js +74 -26
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +105 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +156 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +33 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +32 -2
- package/dist/models/anovaSequential.js +170 -28
- package/dist/models/aovEz.js +154 -39
- package/dist/models/aovStrata.js +68 -24
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +78 -33
- package/dist/models/coxph.d.ts +6 -0
- package/dist/models/coxph.js +166 -69
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +57 -7
- package/dist/models/glm.js +427 -74
- package/dist/models/glmAnova.js +90 -14
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +121 -29
- package/dist/models/glmFamily.d.ts +11 -6
- package/dist/models/glmFamily.js +247 -62
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +246 -37
- package/dist/models/lmer.d.ts +31 -7
- package/dist/models/lmer.js +129 -42
- package/dist/models/lmerAnova.d.ts +3 -3
- package/dist/models/lmerAnova.js +47 -9
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +13 -6
- package/dist/models/lmerTest.js +82 -29
- package/dist/models/mauchly.d.ts +6 -1
- package/dist/models/mauchly.js +41 -15
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +10 -4
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +47 -17
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +12 -1
- package/dist/models/survival.js +75 -28
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +72 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +111 -16
- package/dist/numerics/interp.d.ts +40 -9
- package/dist/numerics/interp.js +375 -55
- package/dist/numerics/ode.js +59 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +97 -10
- package/dist/random/beta.js +58 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +50 -5
- package/dist/random/extra.js +55 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +47 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +31 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/rng.js +4 -0
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +63 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +17 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +175 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +4 -1
- package/dist/special/choose.js +24 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +11 -2
- package/dist/special/incbet.js +30 -4
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +117 -20
- package/dist/special/log1pmx.js +4 -0
- package/dist/special/psigamma.js +7 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -11
- package/llms.txt +15 -6
- package/package.json +19 -10
- package/dist/chunks/chunk-3THFTB36.js +0 -2
- package/dist/chunks/chunk-3TSWYE5L.js +0 -2
- package/dist/chunks/chunk-3WPU6LGK.js +0 -2
- package/dist/chunks/chunk-5ITR67MB.js +0 -2
- package/dist/chunks/chunk-5NRFU6F6.js +0 -2
- package/dist/chunks/chunk-E2LCSVQV.js +0 -2
- package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
- package/dist/chunks/chunk-FKAKALOZ.js +0 -2
- package/dist/chunks/chunk-HD73UKPT.js +0 -2
- package/dist/chunks/chunk-IUULP3LE.js +0 -2
- package/dist/chunks/chunk-JQG3YQOC.js +0 -2
- package/dist/chunks/chunk-KT66SB7R.js +0 -2
- package/dist/chunks/chunk-MAUAOQG3.js +0 -2
- package/dist/chunks/chunk-MDYE7QP2.js +0 -2
- package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
- package/dist/chunks/chunk-PMJI5QO6.js +0 -3
- package/dist/chunks/chunk-UF7KOTHF.js +0 -3
- package/dist/chunks/chunk-UOE57JGT.js +0 -2
- package/dist/chunks/chunk-USPEBXSR.js +0 -2
- package/dist/chunks/chunk-VLUL2HFW.js +0 -3
- package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/descriptive/rank.js
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
// (or before) all the others in their order of appearance. "random" breaks ties with R's uniform random numbers, one
|
|
5
5
|
// per non-missing value, so the result follows setSeed as R's follows set.seed.
|
|
6
6
|
import { runif } from "../random/continuous.js";
|
|
7
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
8
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
9
|
+
const RANK_KEYS = ["tiesMethod", "naLast"];
|
|
7
10
|
/** Ranks of values without NaN */
|
|
8
11
|
function rankValues(x, method) {
|
|
9
12
|
const n = x.length;
|
|
@@ -12,7 +15,8 @@ function rankValues(x, method) {
|
|
|
12
15
|
const u = method === "random" ? runif(n) : [];
|
|
13
16
|
const idx = Array.from({ length: n }, (_, i) => i);
|
|
14
17
|
idx.sort((a, b) => {
|
|
15
|
-
|
|
18
|
+
// compared, not subtracted: Infinity - Infinity is NaN, which would hide the tie
|
|
19
|
+
const d = x[a] < x[b] ? -1 : x[a] > x[b] ? 1 : 0;
|
|
16
20
|
if (d !== 0)
|
|
17
21
|
return d;
|
|
18
22
|
if (method === "first")
|
|
@@ -49,11 +53,14 @@ function rankValues(x, method) {
|
|
|
49
53
|
* @category Descriptive statistics
|
|
50
54
|
*/
|
|
51
55
|
export function rank(x, options = {}) {
|
|
56
|
+
checkOptions(options, RANK_KEYS, "rank"); // generated: option-keys.mjs
|
|
52
57
|
const method = options.tiesMethod ?? "average";
|
|
53
58
|
if (!["average", "first", "last", "random", "max", "min"].includes(method)) {
|
|
54
59
|
throw new RangeError(`invalid tiesMethod "${method}"`);
|
|
55
60
|
}
|
|
56
61
|
const naLast = options.naLast ?? "last";
|
|
62
|
+
if (naLast !== "last" && naLast !== "first" && naLast !== "keep")
|
|
63
|
+
throw new RangeError(`invalid 'naLast': ${String(naLast)}`);
|
|
57
64
|
const xs = Array.from(x);
|
|
58
65
|
const present = xs.filter((v) => !Number.isNaN(v));
|
|
59
66
|
const r = rankValues(present, method);
|
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
import type { Sample } from "../htest/types.js";
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
3
|
+
* Options for {@link tabulate}.
|
|
4
|
+
*
|
|
5
|
+
* @category Descriptive statistics
|
|
6
|
+
*/
|
|
7
|
+
export interface TabulateOptions {
|
|
8
|
+
/** Number of bins. Default max(1, bin); truncated towards 0, as R does. */
|
|
9
|
+
nbins?: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others, NaN, infinite values and values
|
|
13
|
+
* beyond the integer range of R are not counted).
|
|
14
|
+
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin) and is truncated towards 0, as R does; it is the
|
|
15
|
+
* second argument or the option `nbins` (giving both is a RangeError).
|
|
5
16
|
*
|
|
6
17
|
* @example
|
|
7
18
|
* ```ts
|
|
@@ -12,6 +23,15 @@ import type { Sample } from "../htest/types.js";
|
|
|
12
23
|
* @category Descriptive statistics
|
|
13
24
|
*/
|
|
14
25
|
export declare function tabulate(bin: Sample, nbins?: number): number[];
|
|
26
|
+
/**
|
|
27
|
+
* Counts of the integers 1..nbins in `bin`, with the number of bins in the options: `tabulate(bin, { nbins: 3 })`.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* tabulate([1, 2, 2, 5], { nbins: 3 }); // [1, 2, 0]
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare function tabulate(bin: Sample, options: TabulateOptions): number[];
|
|
15
35
|
/**
|
|
16
36
|
* Options for {@link table}.
|
|
17
37
|
*
|
|
@@ -64,7 +84,7 @@ export interface CutOptions {
|
|
|
64
84
|
/**
|
|
65
85
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
66
86
|
*
|
|
67
|
-
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left
|
|
87
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left are an error), or a
|
|
68
88
|
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
69
89
|
* each end, as R does. That range must be finite.
|
|
70
90
|
*
|
|
@@ -6,20 +6,25 @@
|
|
|
6
6
|
// are made as R's factor() makes them: numbers with the same 15-digit text are one level (src/internal/levels.ts).
|
|
7
7
|
import { numberLevels } from "../internal/levels.js";
|
|
8
8
|
import { seqLength } from "../internal/seq.js";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
9
|
+
import { maxOf, minOf } from "../internal/extremes.js";
|
|
10
|
+
import { optionalArgs } from "../internal/optionalArgs.js";
|
|
11
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
12
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
13
|
+
import { optionsIn } from "../internal/optionalArgs.js";
|
|
14
|
+
const TABULATE_KEYS = ["nbins"];
|
|
15
|
+
const TABLE_KEYS = ["useNA"];
|
|
16
|
+
const CUT_KEYS = ["right", "includeLowest"];
|
|
17
|
+
const FIND_INTERVAL_KEYS = ["rightmostClosed", "allInside", "leftOpen"];
|
|
18
|
+
export function tabulate(bin, ...args) {
|
|
19
|
+
checkOptions(optionsIn(args), TABULATE_KEYS, "tabulate"); // generated: option-keys.mjs
|
|
20
|
+
const { nbins } = optionalArgs(["nbins"], args);
|
|
21
|
+
// as R's as.integer: truncated, and NA (here NaN) when infinite or outside the integer range, so such a value is
|
|
22
|
+
// not counted and does not set the default nbins (Infinity was an array of infinite length, 3e9 ran out of memory,
|
|
23
|
+
// #225)
|
|
24
|
+
const b = Array.from(bin, (v) => {
|
|
25
|
+
const t = Math.trunc(v);
|
|
26
|
+
return t >= -2147483647 && t <= 2147483647 ? t : NaN;
|
|
27
|
+
});
|
|
23
28
|
if (nbins !== undefined) {
|
|
24
29
|
if (Number.isNaN(nbins))
|
|
25
30
|
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
@@ -28,7 +33,7 @@ export function tabulate(bin, nbins) {
|
|
|
28
33
|
if (Math.trunc(nbins) >= 2 ** 31)
|
|
29
34
|
throw new RangeError("attempt to make a table with >= 2^31 elements");
|
|
30
35
|
}
|
|
31
|
-
const nb = nbins === undefined ? Math.max(1,
|
|
36
|
+
const nb = nbins === undefined ? Math.max(1, maxOf(b.filter((v) => !Number.isNaN(v)))) : Math.trunc(nbins);
|
|
32
37
|
const out = new Array(Math.max(0, nb)).fill(0);
|
|
33
38
|
for (const v of b)
|
|
34
39
|
if (v >= 1 && v <= nb)
|
|
@@ -48,7 +53,11 @@ export function tabulate(bin, nbins) {
|
|
|
48
53
|
* @category Descriptive statistics
|
|
49
54
|
*/
|
|
50
55
|
export function table(x, options = {}) {
|
|
56
|
+
checkOptions(options, TABLE_KEYS, "table"); // generated: option-keys.mjs
|
|
51
57
|
const useNA = options.useNA ?? "no";
|
|
58
|
+
// (as R's match.arg; any other value was taken as "no", silently dropping the count of missing values; issue #18)
|
|
59
|
+
if (useNA !== "no" && useNA !== "ifany" && useNA !== "always")
|
|
60
|
+
throw new RangeError("'arg' should be one of “no”, “ifany”, “always”");
|
|
52
61
|
const xs = numberLevels(Array.from(x));
|
|
53
62
|
const map = new Map();
|
|
54
63
|
let nas = 0;
|
|
@@ -91,7 +100,7 @@ export function unique(x) {
|
|
|
91
100
|
/**
|
|
92
101
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
93
102
|
*
|
|
94
|
-
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left
|
|
103
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left are an error), or a
|
|
95
104
|
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
96
105
|
* each end, as R does. That range must be finite.
|
|
97
106
|
*
|
|
@@ -104,6 +113,7 @@ export function unique(x) {
|
|
|
104
113
|
* @category Descriptive statistics
|
|
105
114
|
*/
|
|
106
115
|
export function cut(x, breaks, options = {}) {
|
|
116
|
+
checkOptions(options, CUT_KEYS, "cut"); // generated: option-keys.mjs
|
|
107
117
|
const right = options.right ?? true;
|
|
108
118
|
const includeLowest = options.includeLowest ?? false;
|
|
109
119
|
const xs = Array.from(x);
|
|
@@ -114,8 +124,8 @@ export function cut(x, breaks, options = {}) {
|
|
|
114
124
|
throw new RangeError("invalid number of intervals");
|
|
115
125
|
const nb = Math.trunc(k + 1);
|
|
116
126
|
const present = xs.filter((v) => !Number.isNaN(v));
|
|
117
|
-
const lo =
|
|
118
|
-
const hi =
|
|
127
|
+
const lo = minOf(present);
|
|
128
|
+
const hi = maxOf(present);
|
|
119
129
|
// R's errors for a range that is not finite: the same infinity everywhere fails before the checks of the ends
|
|
120
130
|
if (present.length > 0 && lo === hi && !Number.isFinite(lo))
|
|
121
131
|
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
@@ -134,8 +144,12 @@ export function cut(x, breaks, options = {}) {
|
|
|
134
144
|
br[nb - 1] = hi + dx / 1000;
|
|
135
145
|
}
|
|
136
146
|
}
|
|
137
|
-
else
|
|
147
|
+
else {
|
|
138
148
|
br = breaks.filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
|
|
149
|
+
// no interval to code: the error of one break (R gives NA codes for none, or one left after dropping NaN; #227)
|
|
150
|
+
if (br.length < 2)
|
|
151
|
+
throw new RangeError("invalid number of intervals");
|
|
152
|
+
}
|
|
139
153
|
if (new Set(br).size < br.length)
|
|
140
154
|
throw new RangeError("'breaks' are not unique");
|
|
141
155
|
return binCode(xs, br, right, includeLowest);
|
|
@@ -150,7 +164,7 @@ function binCode(xs, br, right, includeLowest) {
|
|
|
150
164
|
let lo = 0;
|
|
151
165
|
let hi = nb;
|
|
152
166
|
while (lo < hi) {
|
|
153
|
-
const mid = (lo + hi) >> 1
|
|
167
|
+
const mid = Math.floor((lo + hi) / 2); // not >> 1, which wraps beyond 2^31 breaks (issue #340)
|
|
154
168
|
if (right ? br[mid] < v : br[mid] <= v)
|
|
155
169
|
lo = mid + 1;
|
|
156
170
|
else
|
|
@@ -178,6 +192,7 @@ function binCode(xs, br, right, includeLowest) {
|
|
|
178
192
|
* @category Descriptive statistics
|
|
179
193
|
*/
|
|
180
194
|
export function findInterval(x, vec, options = {}) {
|
|
195
|
+
checkOptions(options, FIND_INTERVAL_KEYS, "findInterval"); // generated: option-keys.mjs
|
|
181
196
|
const n = vec.length;
|
|
182
197
|
for (let i = 1; i < n; i++) {
|
|
183
198
|
if (!(vec[i] >= vec[i - 1]))
|
|
@@ -200,7 +215,7 @@ export function findInterval(x, vec, options = {}) {
|
|
|
200
215
|
let lo = 0;
|
|
201
216
|
let hi = n;
|
|
202
217
|
while (lo < hi) {
|
|
203
|
-
const mid = (lo + hi) >> 1
|
|
218
|
+
const mid = Math.floor((lo + hi) / 2); // not >> 1 (issue #340)
|
|
204
219
|
if (leftOpen ? vec[mid] < v : vec[mid] <= v)
|
|
205
220
|
lo = mid + 1;
|
|
206
221
|
else
|
package/dist/descriptive.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.
|
|
2
|
-
import{l as me,m as he,n as pe}from"./chunks/chunk-5ITR67MB.js";import"./chunks/chunk-USPEBXSR.js";import{A as Fe,B as je,C as Se,D as Te,E as _e,F as Ie,a as V,b as L,c as z,d as k,e as K,f as ge,g as de,j as ye,k as we,l as Y,m as be,n as Ne,o as Ee,p as Ae,q as Me,r as C,s as F,t as S,u as xe,v as $e,w as ve,x as Oe,y as Re,z as ke}from"./chunks/chunk-JQG3YQOC.js";import{a as ee,b as Le,c as Ce,d as Pe,e as Ue,f as qe}from"./chunks/chunk-MAUAOQG3.js";import"./chunks/chunk-IUULP3LE.js";import"./chunks/chunk-3WPU6LGK.js";import{a as G,e as I,f as J}from"./chunks/chunk-3THFTB36.js";import"./chunks/chunk-FCNVTIPJ.js";import{a as H}from"./chunks/chunk-HD73UKPT.js";import{b as _,c as X}from"./chunks/chunk-VLUL2HFW.js";import"./chunks/chunk-3TSWYE5L.js";import"./chunks/chunk-KT66SB7R.js";var B=4*Number.EPSILON,Ve={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function ze(e,n,t){let r=e.length,o=i=>e[Math.min(Math.max(i,1),r)-1];if(t===7){let i=1+(r-1)*n,h=Math.floor(i),m=o(h),y=o(Math.ceil(i));if(i>h&&y!==m){let g=i-h;return(1-g)*m+g*y}return m}let a,s;if(t<=3){let i=t===3?r*n-.5:r*n;a=Math.floor(i*(1+B)),t===1?s=i>a?1:0:t===2?s=i>a?1:.5:s=i!==a||Math.abs(a%2)===1?1:0}else{let[i,h]=Ve[t],m=i+n*(r+1-i-h);a=Math.floor(m*(1+B)),s=m-a,Math.abs(s)<B&&(s=0)}let l=o(a),f=o(a+1);return s===1?f:s>0&&s<1&&l!==f?(1-s)*l+s*f:l}function P(e,n=[0,.25,.5,.75,1],t={}){let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=Y(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let a=o.sort((i,h)=>i-h),s=typeof n=="number"?[n]:Array.from(n),l=100*Number.EPSILON;if(s.some(i=>i<-l||i>1+l))throw new RangeError("'probs' outside [0,1]");let f=s.map(i=>Number.isNaN(i)||a.length===0?NaN:ze(a,Math.min(Math.max(i,0),1),r));return typeof n=="number"?f[0]:f}function W(e,n={}){let[t,r]=P(e,[.25,.75],n);return r-t}function Be(e){let n=Array.from(e).filter(a=>!Number.isNaN(a)).sort((a,s)=>a-s),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(a=>.5*(n[Math.floor(a)-1]+n[Math.ceil(a)-1]))}function We(e,n={}){let t=Array.from(e),r=t.filter(m=>!Number.isNaN(m)),o=n.naRm?r:t,a=n.center??(o.length>r.length?NaN:F(r)),s=n.constant??1.4826,l=n.low??!1,f=n.high??!1,i=o.map(m=>Math.abs(m-a)),h=i.length;if((l||f)&&h%2===0){if(l&&f)throw new RangeError("'low' and 'high' cannot be both TRUE");let m=h/2+(f?1:0),y=i.filter(g=>!Number.isNaN(g)).sort((g,d)=>g-d);if(m===0||y.length<m)throw new RangeError(`'partial' index ${m} outside bounds`);return s*y[m-1]}return s*F(i)}var ne=e=>e===null||typeof e=="number"&&Number.isNaN(e),te=e=>Array.isArray(e)||ArrayBuffer.isView(e);function Ze(e){if(te(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function re(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(Ze),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,a)=>r.every(s=>!ne(s[a])))}function De(e){if(te(e))return Array.from(e).filter(r=>!ne(r));let n=re(e),t={};for(let[r,o]of Object.entries(e)){let a=Array.from(o).filter((s,l)=>n[l]);t[r]=o instanceof Float64Array?Float64Array.from(a):a}return t}function oe(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5;if(Number.isNaN(r)||Math.abs(r)>=2**31||Math.trunc(r)<0)throw new RangeError("invalid 'n' argument");let o=Math.trunc(r),a=n.minN??Math.floor(r/3);if(Number.isNaN(a)||Math.trunc(a)<0||Math.trunc(a)>o)throw new RangeError("invalid 'min.n' argument");let s=Math.trunc(a),l=n.shrinkSml??.75,f=n.highUBias??1.5,i=n.u5Bias??.5+1.5*f,h=1/0,m=-1/0;for(let A of t)A<h&&(h=A),A>m&&(m=A);let y=m-h,g,d;if(y===0&&m===0)g=1,d=!0;else{g=Math.max(Math.abs(h),Math.abs(m));let O=(1+(i>=1.5*f+.5?1/(1+f):1.5/(1+i)))*Math.max(1,o)*Number.EPSILON;d=y<g*O*3}d?(g>10&&(g=9+g/10),g*=l,s>1&&(g/=s)):(g=o>1?y/o:y,y===1/0&&o>=2&&(g=m/o-h/o));let x=2**-20*Qe;g<x?g=x:g>Number.MAX_VALUE/1.25&&(g=Number.MAX_VALUE/1.25);let b=10**Math.floor(Math.log10(g)),w=[[2*b,f],[5*b,i],[10*b,f]],c=b;for(let[A,O]of w)if(A-g<O*(g-c))c=A;else break;let u=1e-10,p=Math.floor(h/c+u);for(;p*c>h+u*c;)p--;for(;!Number.isFinite(p*c);)p++;let N=Math.ceil(m/c-u);for(;N*c<m-u*c;)N++;for(;!Number.isFinite(N*c);)N--;let E=Math.trunc(.5+N-p);if(E<s){let A=s-E,O=Math.floor(A/2),T=A%2;h===0&&p===0&&m!==0?N+=A:m===0&&N===0&&h!==0?p-=A:p>=0?(N+=O,p-=O+T):(p-=O,N+=O+T),E=s}let $=p*c<h?p*c:h,M=N*c>m?N*c:m;if(E<=0)return[$];let v;if(Number.isFinite(M-$))v=ee($,M,E+1);else{let A=M/E-$/E;v=Array.from({length:E+1},(O,T)=>$+T*A),v[E]=M}let R=M/E-$/E;return v.map(A=>Math.abs(A)<1e-14*R?0:A)}var Qe=22250738585072014e-324;function Ge(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function Je(e,n){let t=e.length,[r,o]=S(e),a=o-r;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let s=3.5*C(e)*t**-.3333333333333333;return s>0?Math.max(1,Math.ceil(a/s)):1}case"fd":case"freedman-diaconis":{let s=e.map(Ge),l=2*W(s);for(let f=1/8;l===0&&f>=1/512;f/=2){let[i,h]=P(s,[f,1-f]);l=(h-i)/(1-2*f)}return l===0&&(l=3.5*C(e)),l>0?Math.ceil(a/l*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Xe(e,n){let t=e.slice(1).map((r,o)=>r-e[o]);return e.length>5?F(t):e.length<=3?n:Math.min(...t.filter(r=>r>0))}function He(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,a=n.includeLowest??!0,s=n.breaks??"Sturges",l;if(typeof s!="string"&&typeof s!="number"&&s.length>1)l=[...s].sort((w,c)=>w-c);else{a=!0;let w=typeof s=="string"?Je(t,s):typeof s=="number"?s:s[0];if(!Number.isFinite(w)||w<1)throw new RangeError("invalid number of 'breaks'");w=Math.min(w,1e6);let[c,u]=S(t);l=oe([c,u],{n:w,minN:1});for(let p=1;p<l.length;p++)if(!(l[p]-l[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=l.length,[i,h]=r>0?S(t):[0,0],m=1e-7*Xe(l,h-i),y=l.map((w,c)=>o?c===0&&a?w-m:w+m:c<f-1?w-m:a?w+m:w-m),g=new Array(Math.max(0,f-1)).fill(0),d=0;for(let w of t){let c=Ke(w,y,o,a);c>=0&&(g[c]++,d++)}if(d<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let x=g.map((w,c)=>w/(r*(l[c+1]-l[c]))),b=g.map((w,c)=>.5*(l[c+1]+l[c]));return{breaks:l,counts:g,density:x,mids:b}}function Ke(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let l=1,f=o;for(;l<f;){let i=l+f>>1;e<=n[i]?f=i:l=i+1}return l-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let a=0,s=o-1;for(;a<s;){let l=a+s+1>>1;n[l]<=e?a=l:s=l-1}return a}function Ye(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,a=t;for(;o<a;){let s=o+a>>1;n[s]<=r?o=s+1:a=s}return o/t}}var U=e=>e===null||typeof e=="number"&&Number.isNaN(e),en=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?H(e,n):Number(e)-Number(n),nn=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?_(e):e>0?"Inf":"-Inf";function tn(e,n){let t=X(n),r=new Set(t.filter(l=>!U(l)).map(l=>typeof l));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let a=[...new Set(t.filter(l=>!U(l)))].sort(en),s=new Map(a.map((l,f)=>[l,f]));return{levels:a,codes:t.map(l=>U(l)?-1:s.get(l))}}var j=e=>Array.isArray(e)||e instanceof Float64Array;function ie(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(j))return[...e];if(e.some(j))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function Z(e,n,t){e.forEach((s,l)=>{if(s.length!==t)throw new RangeError(`${n[l]} must have one label per row (${t}), not ${s.length}`)});let r=e.map((s,l)=>tn(n[l],s)),o=r.reduce((s,l)=>s*l.levels.length,1),a=new Array(t);for(let s=0;s<t;s++){let l=0,f=1;for(let i of r){let h=i.codes[s];if(h<0){l=-1;break}l+=h*f,f*=i.levels.length}a[s]=l}return{factors:r,size:o,cells:a}}function D(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function rn(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var ce=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function on(e,n,t){let r=Array.from(e),o=ie(n),a=Z(o,ce(o.length,"index"),r.length),s=D(a).map(i=>i.length===0?null:{value:t(i.map(h=>r[h]))}),f=s.every(i=>i===null||typeof i.value=="number")?s.map(i=>i===null?NaN:i.value):s.map(i=>i===null?null:i.value);return{dim:a.factors.map(i=>i.levels.length),dimnames:a.factors.map(i=>[...i.levels]),values:f}}function sn(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=o instanceof Float64Array?Float64Array.from(n,a=>o[a]):n.map(a=>o[a]);return t}function ln(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!j(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function an(e,n,t={}){let r=t.sep??".",o=ie(n),a=!j(e);if(a&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let s=a?ln(e):e.length,l=Z(o,ce(o.length,"f"),s),f=a?[]:Array.from(e),i=new Map;return D(l).forEach((h,m)=>{if(h.length===0&&(t.drop||l.factors.length===1))return;let y=rn(l,m).map(nn).join(r);i.set(y,a?sn(e,h):h.map(g=>f[g]))}),i}function se(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!j(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function le(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new Error(`object '${n}' not found`);if(!j(t))throw new TypeError(`column '${n}' must be an array`);return t}function cn(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),{rhs:o}=G(`~ ${e.slice(t+1)}`),a=/^[A-Za-z.][A-Za-z0-9._]*$/,s;if(r!=="."){let i=/^cbind\s*\((.*)\)$/s.exec(r);if(s=i===null?[r]:i[1].split(",").map(h=>h.trim()),s.some(h=>!a.test(h)||h==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(I(o,[]).length<I(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let l=s===void 0?[]:n.filter(i=>!s.includes(i)),f=I(o,l);return J(o,()=>0,l),{values:s??n.filter(i=>!f.includes(i)),groups:f}}function ae(e,n,t,r,o,a){let s=r[0]?.length??n[0]?.length??0;e.forEach((h,m)=>{if(n[m].length!==s)throw new RangeError(`variable lengths differ (found for '${h}')`)});let l=Z(r,t,s),f=D(l).map((h,m)=>({cell:m,rows:h.filter(o)})).filter(h=>h.rows.length>0),i={};return t.forEach((h,m)=>{let y=r[m];i[h]=f.map(g=>{let d=y[g.rows[0]];return d===0?0:d})}),e.forEach((h,m)=>{let y=n[m],d=f.map(b=>a(b.rows.map(w=>y[w]))).map(b=>{if(typeof b=="number")return{names:void 0,values:[b]};if(Array.isArray(b))return{names:void 0,values:[...b]};let w=b;return{names:Object.keys(w),values:Object.values(w)}}),x=d[0]?.values.length??1;if(d.some(b=>b.values.length!==x))throw new RangeError("fun must return values of the same length for every group");if(x===1&&d[0]?.names===void 0){i[h]=d.map(b=>b.values[0]);return}for(let b=0;b<x;b++){let w=d[0].names?.[b]??String(b+1);i[`${h}.${w}`]=d.map(c=>c.values[b])}}),i}function un(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let l=n,{values:f,groups:i}=cn(e,Object.keys(l)),h=d=>Object.prototype.hasOwnProperty.call(l,d),m=f.map(d=>se(d,h(d)?l[d]:void 0)),y=i.map(d=>le(l,d));return ae(f,m,i,y,d=>m.every(x=>!Number.isNaN(x[d]))&&y.every(x=>!U(x[d])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(l=>se(l,e[l])),a=Object.keys(n);if(a.length===0)throw new RangeError("'by' must name at least one grouping column");let s=a.map(l=>le(n,l));return ae(r,o,a,s,()=>!0,t)}var q=e=>typeof e=="string"?[e]:[...e];function fe(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function fn(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function mn(e,n){let t=null;for(let r of n){let o=fn(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function hn(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new Error(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(a=>{let s=o.exec(a);return Array.from({length:t},(l,f)=>s===null?null:s[f+1]??null)})}function pn(e,n,t,r){let o=new RegExp(n,"g"),a=[],s=[],l=e.map((i,h)=>{let m=[],y=0;for(let g of i.matchAll(o))g[0].length!==0&&(m.push(i.slice(y,g.index)),y=g.index+g[0].length);return m.push(i.slice(y)),m.length>t&&a.push(h+1),m.length<t&&s.push(h+1),Array.from({length:t},(g,d)=>m[d]??null)}),f=i=>`${i.length} rows [${i.join(", ")}]`;return a.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(a)}.`),s.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(s)}.`),l}function gn(e,n,t,r){let{namesSep:o,namesPattern:a}=t;if(n.length===1){if(o!==void 0)throw new Error("`names_sep` can't be used with a length 1 `names_to`.");if(a===void 0)return e.map(l=>[l]);let s=new RegExp(a);return e.map(l=>[s.exec(l)?.[1]??null])}if(o===void 0==(a===void 0))throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?pn(e,o,n.length,r):hn(e,a,n.length)}function dn(e,n){let t=V(e),r=Object.keys(e),o=typeof n.cols=="function"?r.filter(n.cols):[...new Set(n.cols)];if(fe(e,o),o.length===0)throw new Error("`cols` must select at least one column.");let a=q(n.namesTo??"name"),s=a.indexOf(".value");if(a.lastIndexOf(".value")!==s)throw new Error('`names_to` may contain ".value" only once');let l=[],f=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),i=o.map(c=>f===null?c:c.replace(f,"")),h=gn(i,a,n,l),m=[],y=[];if(s<0)m.push(...h),y.push({name:n.valuesTo??"value",sources:[...o]});else{let c=new Map,u=new Map;h.forEach((p,N)=>{let E=p.filter((A,O)=>O!==s),$=JSON.stringify(E),M=c.get($);if(M===void 0){M=m.length,c.set($,M),m.push(E);for(let A of y)A.sources.push(null)}let v=p[s]??"NA",R=u.get(v);if(R===void 0&&(R={name:v,sources:m.map(()=>null)},u.set(v,R),y.push(R)),R.sources[M]!==null)throw new Error(`the names give the value column '${v}' twice for one key`);R.sources[M]=o[N]})}let g=y.map(c=>mn(e,c.sources.filter(u=>u!==null))),d=[];if(n.colsVary==="slowest")for(let c=0;c<m.length;c++)for(let u=0;u<t;u++)d.push([u,c]);else for(let c=0;c<t;c++)for(let u=0;u<m.length;u++)d.push([c,u]);let x=(c,u,p)=>{let N=c.sources[p];return N==null?null:e[N][u]};n.valuesDropNa===!0&&(d=d.filter(([c,u])=>y.some(p=>!L(x(p,c,u)))));let b={},w=d.map(([c])=>c);for(let c of r)o.includes(c)||k(b,c,z(e[c],w));if(a.forEach((c,u)=>{if(u===s)return;let p=n.namesTransform?.[c],N=E=>{let $=m[E][u<s||s<0?u:u-1];return $===null||p===void 0?$:p($)};k(b,c,d.map(([,E])=>N(E)))}),y.forEach((c,u)=>{let p=g[u]==="double";if(p&&c.sources.every(N=>N!==null&&e[N]instanceof Float64Array))k(b,c.name,Float64Array.from(d,([N,E])=>x(c,N,E)));else{let N=d.map(([E,$])=>{let M=x(c,E,$);return p&&typeof M=="boolean"?Number(M):M});k(b,c.name,N)}}),n.onWarning!==void 0)for(let c of new Set(l))n.onWarning(c);return b}var yn=e=>L(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function ue(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(a,s)=>{let l=JSON.stringify(e.map(i=>yn(i[s]))),f=t.get(l);return f===void 0&&(f=r.length,t.set(l,f),r.push(s)),f}),firsts:r}}function wn(e){return L(e)?"NA":typeof e=="number"?Number.isFinite(e)?_(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function Q(e,n,t){if(e!==void 0)return n(e)?e:e[t]}function bn(e,n={}){let t=V(e),r=q(n.namesFrom??"name"),o=q(n.valuesFrom??"value"),a=n.idCols===void 0?Object.keys(e).filter(u=>!r.includes(u)&&!o.includes(u)):q(n.idCols);fe(e,[...a,...r,...o]);let s=n.namesPrefix??"",l=n.namesSep??"_",f=ue(a.map(u=>e[u]),t),i=ue(r.map(u=>e[u]),t),h=i.firsts.map((u,p)=>p);n.namesSort===!0&&h.sort((u,p)=>{for(let N of r){let E=K(e[N][i.firsts[u]],e[N][i.firsts[p]]);if(E!==0)return E}return 0});let m=i.firsts.map(u=>s+r.map(p=>wn(e[p][u])).join(l)),y=i.firsts.length,g=Array.from({length:f.firsts.length*y},()=>[]);for(let u=0;u<t;u++)g[f.codes[u]*y+i.codes[u]].push(u);let d=u=>typeof u=="function",x=u=>typeof u!="object"||u===null,b=(u,p)=>{let N=e[u],E=Q(n.valuesFn,d,u),$=Q(n.valuesFill,x,u)??null,M=f.firsts.map((v,R)=>{let A=g[R*y+p];return A.length===0?$:E!==void 0?E(A.map(O=>N[O])):N[A[0]]});return N instanceof Float64Array&&M.every(v=>v===null||typeof v=="number")?Float64Array.from(M,v=>v===null?NaN:v):M};for(let u of o)if(Q(n.valuesFn,d,u)===void 0&&g.some(p=>p.length>1))throw new Error(`values from '${u}' are not uniquely identified; use valuesFn to summarise them`);let w={};for(let u of a)k(w,u,z(e[u],f.firsts));let c=(u,p)=>o.length===1?m[p]:`${u}${l}${m[p]}`;if(n.namesVary==="slowest")for(let u of h)for(let p of o)k(w,c(p,u),b(p,u));else for(let u of o)for(let p of h)k(w,c(u,p),b(u,p));return w}export{W as IQR,un as aggregate,re as completeCases,pe as cor,he as cov,ve as cummax,Oe as cummin,$e as cumprod,xe as cumsum,Ue as cut,_e as cv,Re as diff,Ye as ecdf,qe as findInterval,Be as fivenum,ye as fromRows,je as geometricMean,He as hist,Fe as kurtosis,We as mad,Ee as mean,Te as meanAD,F as median,ge as merge,Se as modes,De as naOmit,dn as pivotLonger,bn as pivotWider,oe as pretty,Ne as prod,P as quantile,S as range,me as rank,Ie as scale,C as sd,ke as skewness,an as split,de as subset,be as sum,Ce as table,Le as tabulate,on as tapply,we as toRows,Pe as unique,Me as variance,Ae as weightedMean};
|
|
1
|
+
/*! rStats.js 0.17.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
|
|
2
|
+
import{m as ke,n as Fe,o as Te}from"./chunks/chunk-34S5SQY6.js";import"./chunks/chunk-CZI7KUO3.js";import{A as De,B as Qe,C as Ze,D as Ge,E as Je,F as Xe,a as Z,b as W,c as G,d as F,e as fe,f as Se,g as _e,j as Ie,k as je,l as me,m as Ce,n as Le,o as Pe,p as Ve,q as Ue,r as z,s as j,t as C,u as qe,v as Ye,w as Ke,x as We,y as ze,z as Be}from"./chunks/chunk-FY3FVOBM.js";import{a as he,b as He,c as en,d as nn,e as tn,f as rn}from"./chunks/chunk-ZFQWB222.js";import"./chunks/chunk-ONY5CISH.js";import"./chunks/chunk-RFE7MVP7.js";import{a as ae,e as K,f as ie}from"./chunks/chunk-NSYZTS26.js";import"./chunks/chunk-LV3W2F7N.js";import{a as ue}from"./chunks/chunk-H3WVPZDL.js";import{b as le}from"./chunks/chunk-DXI5N2ET.js";import{b as Y,d as ce}from"./chunks/chunk-C7V2FH6L.js";import{b as q,c as se}from"./chunks/chunk-SE7V2KLO.js";import"./chunks/chunk-LHUIJQHY.js";import{P as Q,l as S,u as V}from"./chunks/chunk-WM7VFXTV.js";var on=["type","naRm"],sn=["type","naRm"],ln=["center","constant","low","high","naRm"],J=4*Number.EPSILON,an={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function cn(e,n,t){let r=e.length,o=i=>e[Math.min(Math.max(i,1),r)-1];if(t===7){let i=1+(r-1)*n,m=Math.floor(i),c=o(m),p=o(Math.ceil(i));if(i>m&&p!==c){let h=i-m;return(1-h)*c+h*p}return c}let a,s;if(t<=3){let i=t===3?r*n-.5:r*n;a=Math.floor(i*(1+J)),t===1?s=i>a?1:0:t===2?s=i>a?1:.5:s=i!==a||Math.abs(a%2)===1?1:0}else{let[i,m]=an[t],c=i+n*(r+1-i-m);a=Math.floor(c*(1+J)),s=c-a,Math.abs(s)<J&&(s=0)}let l=o(a),f=o(a+1);return s===1?f:s>0&&s<1&&l!==f?(1-s)*l+s*f:l}function B(e,n=[0,.25,.5,.75,1],t={}){S(t,on,"quantile");let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=me(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let a=o.sort((i,m)=>i-m),s=typeof n=="number"?[n]:Array.from(n),l=100*Number.EPSILON;if(s.some(i=>i<-l||i>1+l))throw new RangeError("'probs' outside [0,1]");let f=s.map(i=>Number.isNaN(i)||a.length===0?NaN:cn(a,Math.min(Math.max(i,0),1),r));return typeof n=="number"?f[0]:f}function X(e,n={}){S(n,sn,"IQR");let[t,r]=B(e,[.25,.75],n);return r-t}function un(e){let n=Array.from(e).filter(a=>!Number.isNaN(a)).sort((a,s)=>a-s),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(a=>q(n[Math.floor(a)-1],n[Math.ceil(a)-1]))}function fn(e,n={}){S(n,ln,"mad");let t=Array.from(e),r=t.filter(c=>!Number.isNaN(c)),o=n.naRm?r:t,a=n.center??(o.length>r.length?NaN:j(r)),s=n.constant??1.4826,l=n.low??!1,f=n.high??!1,i=o.map(c=>Math.abs(c-a)),m=i.length;if((l||f)&&m%2===0){if(l&&f)throw new RangeError("'low' and 'high' cannot be both TRUE");let c=m/2+(f?1:0),p=i.filter(h=>!Number.isNaN(h)).sort((h,N)=>h-N);if(c===0||p.length<c)throw new RangeError(`'partial' index ${c} outside bounds`);return s*p[c-1]}return s*j(i)}var pe=e=>e===null||typeof e=="number"&&Number.isNaN(e),ge=e=>Array.isArray(e)||ArrayBuffer.isView(e);function mn(e){if(ge(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function de(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(mn),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,a)=>r.every(s=>!pe(s[a])))}function hn(e){if(ge(e))return Array.from(e).filter(r=>!pe(r));let n=de(e),t={};for(let[r,o]of Object.entries(e)){let a=Array.from(o).filter((s,l)=>n[l]);F(t,r,o instanceof Float64Array?Float64Array.from(a):a)}return t}var pn=["breaks","right","includeLowest"],gn=["n","minN","shrinkSml","highUBias","u5Bias"];function we(e,n={}){S(n,gn,"pretty");let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5;if(Number.isNaN(r)||Math.abs(r)>=2**31||Math.trunc(r)<0)throw new RangeError("invalid 'n' argument");let o=Math.trunc(r),a=n.minN??Math.floor(r/3);if(Number.isNaN(a)||Math.trunc(a)<0||Math.trunc(a)>o)throw new RangeError("invalid 'min.n' argument");let s=Math.trunc(a),l=n.shrinkSml??.75;if(!Number.isFinite(l)||l<=0)throw new RangeError("invalid 'shrink.sml' argument");let f=n.highUBias??1.5;if(!Number.isFinite(f)||f<0)throw new RangeError("invalid 'high.u.bias' argument");let i=n.u5Bias??.5+1.5*f;if(!Number.isFinite(i)||i<0)throw new RangeError("invalid 'u5.bias' argument");let m=1/0,c=-1/0;for(let R of t)R<m&&(m=R),R>c&&(c=R);let p=c-m,h,N;if(p===0&&c===0)h=1,N=!0;else{h=Math.max(Math.abs(m),Math.abs(c));let $=(1+(i>=1.5*f+.5?1/(1+f):1.5/(1+i)))*Math.max(1,o)*Number.EPSILON;N=p<h*$*3}N?(h>10&&(h=9+h/10),h*=l,s>1&&(h/=s)):(h=o>1?p/o:p,p===1/0&&o>=2&&(h=c/o-m/o));let E=2**-20*dn;h<E?h=E:h>Number.MAX_VALUE/1.25&&(h=Number.MAX_VALUE/1.25);let M=10**Math.floor(Math.log10(h)),g=[[2*M,f],[5*M,i],[10*M,f]],y=M;for(let[R,$]of g)if(R-h<$*(h-y))y=R;else break;let d=1e-10,w=Math.floor(m/y+d);for(;w*y>m+d*y;)w--;for(;!Number.isFinite(w*y);)w++;let x=Math.ceil(c/y-d);for(;x*y<c-d*y;)x++;for(;!Number.isFinite(x*y);)x--;let u=Math.trunc(.5+x-w);if(u<s){let R=s-u,$=Math.floor(R/2),k=R%2;m===0&&w===0&&c!==0?x+=R:c===0&&x===0&&m!==0?w-=R:w>=0?(x+=$,w-=$+k):(w-=$,x+=$+k),u=s}let b=w*y<m?w*y:m,v=x*y>c?x*y:c;if(u<=0)return[b];let O=he(b,v,u+1),A=v/u-b/u;return O.map(R=>Math.abs(R)<1e-14*A?0:R)}var dn=22250738585072014e-324;function wn(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function yn(e,n){let t=e.length;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let r=l=>[C(l),3.5*z(l)*t**-.3333333333333333],[[o,a],s]=r(e);return Number.isFinite(a-o)&&Number.isFinite(s)||([[o,a],s]=r(Q([e]).groups[0])),s>0?Math.max(1,Math.ceil((a-o)/s)):1}case"fd":case"freedman-diaconis":{let r=(f,i)=>{let m=2*X(i);for(let c=.125;m===0&&c>=.001953125;c/=2){let[p,h]=B(i,[c,1-c]);m=(h-p)/(1-2*c)}return m===0&&(m=3.5*z(f)),[C(f),m]},o=e.map(wn),[[a,s],l]=r(e,o);if(!(Number.isFinite(s-a)&&Number.isFinite(l))){let{k:f}=Q([e]);[[a,s],l]=r(e.map(i=>V(i,-f)),o.map(i=>V(i,-f)))}return l>0?Math.ceil((s-a)/l*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function bn(e,n,t){let r=e.slice(1).map((o,a)=>o-e[a]);return e.length>5?1e-7*j(r):e.length<=3?t-n===1/0?2*(1e-7*(t/2-n/2)):1e-7*(t-n):1e-7*se(r.filter(o=>o>0))}function Nn(e,n={}){S(n,pn,"hist");let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,a=n.includeLowest??!0,s=n.breaks??"Sturges",l;if(typeof s!="string"&&typeof s!="number"&&s.length>1){if(!s.every(Number.isFinite))throw new RangeError("'breaks' are not finite");if(l=[...s].sort((g,y)=>g-y),l.some((g,y)=>y>0&&!(g>l[y-1])))throw new RangeError("'breaks' are not strictly increasing")}else{a=!0;let g=typeof s=="string"?yn(t,s):typeof s=="number"?s:s[0];if(!Number.isFinite(g)||g<1)throw new RangeError("invalid number of 'breaks'");g=Math.min(g,1e6);let[y,d]=C(t);l=we([y,d],{n:g,minN:1});for(let w=1;w<l.length;w++)if(!(l[w]-l[w-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=l.length,[i,m]=r>0?C(t):[0,0],c=bn(l,i,m),p=l.map((g,y)=>o?y===0&&a?g-c:g+c:y<f-1?g-c:a?g+c:g-c),h=new Array(Math.max(0,f-1)).fill(0),N=0;for(let g of t){let y=xn(g,p,o,a);y>=0&&(h[y]++,N++)}if(N<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let E=h.map((g,y)=>En(g,r,l[y],l[y+1])),M=h.map((g,y)=>q(l[y+1],l[y]));return{breaks:l,counts:h,density:E,mids:M}}function En(e,n,t,r){let o=r-t;if(!(n*o===1/0&&Number.isFinite(t)&&Number.isFinite(r)))return e/(n*o);let a=o===1/0?1:0,s=a===1?r/2-t/2:o,l=Math.floor(Math.log2(s));return V(e,-(l+a))/(n*V(s,-l))}function xn(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let l=1,f=o;for(;l<f;){let i=Math.floor((l+f)/2);e<=n[i]?f=i:l=i+1}return l-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let a=0,s=o-1;for(;a<s;){let l=Math.floor((a+s+1)/2);n[l]<=e?a=l:s=l-1}return a}function Rn(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,a=t;for(;o<a;){let s=Math.floor((o+a)/2);n[s]<=r?o=s+1:a=s}return o/t}}var vn=["drop","sep"],D=e=>e===null||typeof e=="number"&&Number.isNaN(e),$n=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?ue(e,n):Number(e)-Number(n),An=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?Y(e):e>0?"Inf":"-Inf";function Mn(e,n){let t=ce(n),r=new Set(t.filter(l=>!D(l)).map(l=>typeof l));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let a=[...new Set(t.filter(l=>!D(l)))].sort($n),s=new Map(a.map((l,f)=>[l,f]));return{levels:a,codes:t.map(l=>D(l)?-1:s.get(l))}}var L=e=>Array.isArray(e)||e instanceof Float64Array;function Ee(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(L))return[...e];if(e.some(L))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function H(e,n,t){e.forEach((s,l)=>{if(s.length!==t)throw new RangeError(`${n[l]} must have one label per row (${t}), not ${s.length}`)});let r=e.map((s,l)=>Mn(n[l],s)),o=r.reduce((s,l)=>s*l.levels.length,1);if(o>=2**31)throw new RangeError("total number of levels >= 2^31");let a=new Array(t);for(let s=0;s<t;s++){let l=0,f=1;for(let i of r){let m=i.codes[s];if(m<0){l=-1;break}l+=m*f,f*=i.levels.length}a[s]=l}return{factors:r,size:o,cells:a}}function ee(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function On(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var xe=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function kn(e,n,t){let r=Array.from(e),o=Ee(n),a=H(o,xe(o.length,"index"),r.length),s=ee(a).map(i=>i.length===0?null:{value:t(i.map(m=>r[m]))}),f=s.every(i=>i===null||typeof i.value=="number")?s.map(i=>i===null?NaN:i.value):s.map(i=>i===null?null:i.value);return{dim:a.factors.map(i=>i.levels.length),dimnames:a.factors.map(i=>[...i.levels]),values:f}}function Fn(e,n){let t={};for(let[r,o]of Object.entries(e))F(t,r,o instanceof Float64Array?Float64Array.from(n,a=>o[a]):n.map(a=>o[a]));return t}function Tn(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!L(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function Sn(e,n,t={}){S(t,vn,"split");let r=t.sep??".",o=Ee(n),a=!L(e);if(a&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let s=a?Tn(e):e.length,l=H(o,xe(o.length,"f"),s),f=a?[]:Array.from(e),i=new Map;return ee(l).forEach((m,c)=>{if(m.length===0&&(t.drop||l.factors.length===1))return;let p=On(l,c).map(An).join(r);if(i.has(p))throw new RangeError(`the group names joined with '${r}' are not unique ('${p}'); use another sep`);i.set(p,a?Fn(e,m):m.map(h=>f[h]))}),i}function ye(e,n){if(n===void 0)throw new RangeError(`object '${e}' not found`);if(!L(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function be(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new RangeError(`object '${n}' not found`);if(!L(t))throw new TypeError(`column '${n}' must be an array`);return t}function _n(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),{rhs:o}=ae(`~ ${e.slice(t+1)}`),a=/^[A-Za-z.][A-Za-z0-9._]*$/,s;if(r!=="."){let i=/^cbind\s*\((.*)\)$/s.exec(r);if(s=i===null?[r]:i[1].split(",").map(m=>m.trim()),s.some(m=>!a.test(m)||m==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(K(o,[]).length<K(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let l=s===void 0?[]:n.filter(i=>!s.includes(i)),f=K(o,l);return ie(o,()=>0,l),{values:s??n.filter(i=>!f.includes(i)),groups:f}}function Ne(e,n,t,r,o,a){let s=r[0]?.length??n[0]?.length??0;e.forEach((c,p)=>{if(n[p].length!==s)throw new RangeError(`variable lengths differ (found for '${c}')`)});let l=H(r,t,s),f=ee(l).map((c,p)=>({cell:p,rows:c.filter(o)})).filter(c=>c.rows.length>0),i={};t.forEach((c,p)=>{let h=r[p];F(i,c,f.map(N=>{let E=h[N.rows[0]];return E===0?0:E}))});let m=(c,p)=>{if(Object.hasOwn(i,c))throw new RangeError(`duplicate column name '${c}' in the result`);F(i,c,p)};return e.forEach((c,p)=>{let h=n[p],E=f.map(g=>a(g.rows.map(y=>h[y]))).map(g=>{if(typeof g=="number")return{names:void 0,values:[g]};if(Array.isArray(g))return{names:void 0,values:[...g]};let y=g;return{names:Object.keys(y),values:Object.values(y)}}),M=E[0]?.values.length??1;if(E.some(g=>g.values.length!==M))throw new RangeError("fun must return values of the same length for every group");if(M===1&&E[0]?.names===void 0){m(c,E.map(g=>g.values[0]));return}for(let g=0;g<M;g++){let y=E[0].names?.[g]??String(g+1);m(`${c}.${y}`,E.map(d=>d.values[g]))}}),i}function In(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let l=n,{values:f,groups:i}=_n(e,Object.keys(l)),m=N=>Object.prototype.hasOwnProperty.call(l,N),c=f.map(N=>ye(N,m(N)?l[N]:void 0)),p=i.map(N=>be(l,N));return Ne(f,c,i,p,N=>c.every(E=>!Number.isNaN(E[N]))&&p.every(E=>!D(E[N])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(l=>ye(l,e[l])),a=Object.keys(n);if(a.length===0)throw new RangeError("'by' must name at least one grouping column");let s=a.map(l=>be(n,l));return Ne(r,o,a,s,()=>!0,t)}var jn=new Set(["cols","namesTo","namesPrefix","namesSep","namesPattern","namesTransform","valuesTo","valuesDropNa","colsVary","onWarning"]),Cn=new Set(["namesFrom","valuesFrom","idCols","namesPrefix","namesSep","namesSort","namesVary","valuesFill","valuesFn"]),te=e=>typeof e=="string"?[e]:[...e];function Ae(e,n){if(n==null)return"fastest";if(n==="fastest"||n==="slowest")return n;throw typeof n!="string"?new TypeError(`\`${e}\` must be a string or character vector.`):new RangeError(`\`${e}\` must be one of "fastest" or "slowest", not "${n}".`)}function re(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new RangeError(`Column \`${t}\` doesn't exist.`)}function Me(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function Ln(e,n){let t=null;for(let r of n){let o=Me(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function Re(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new TypeError(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(a=>{let s=o.exec(a);return Array.from({length:t},(l,f)=>s===null?null:s[f+1]??null)})}function Pn(e,n){let t=e.charCodeAt(n);if(t>=55296&&t<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);if(r>=56320&&r<=57343)return 2}return 1}function Vn(e,n,t,r){let o=new RegExp(n,"g"),a=[],s=[],l=e.map((i,m)=>{let c=[],p=0,h=0;for(;;){o.lastIndex=p;let N=o.exec(i);if(N===null||(c.push(i.slice(h,N.index)),h=N.index+N[0].length,p=N[0].length===0?N.index+Pn(i,N.index):h,p>=i.length))break}return c.push(i.slice(h)),c.length>t&&a.push(m+1),c.length<t&&s.push(m+1),Array.from({length:t},(N,E)=>c[E]??null)}),f=i=>`${i.length} rows [${i.join(", ")}]`;return a.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(a)}.`),s.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(s)}.`),l}function ve(e,n){return e!==void 0&&Object.hasOwn(e,n)?e[n]:void 0}function Un(e,n,t,r){let{namesSep:o,namesPattern:a}=t;if(n.length===0)return e.map(()=>[]);if(n.length===1){if(o!==void 0)throw new TypeError("`names_sep` can't be used with a length 1 `names_to`.");return a===void 0?e.map(s=>[s]):Re(e,a,1)}if(o===void 0==(a===void 0))throw new TypeError("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?Vn(e,o,n.length,r):Re(e,a,n.length)}function qn(e,n){S(n,jn,"pivotLonger");let t=Ae("cols_vary",n.colsVary),r=Z(e),o=Object.keys(e),a=typeof n.cols=="function"?o.filter(n.cols):[...new Set(n.cols)];if(re(e,a),a.length===0)throw new RangeError("`cols` must select at least one column.");let s=te(n.namesTo??"name"),l=s.indexOf(".value");if(s.lastIndexOf(".value")!==l)throw new RangeError('`names_to` may contain ".value" only once');let f=[],i=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),m=a.map(d=>i===null?d:d.replace(i,"")),c=Un(m,s,n,f),p=[],h=[];if(l<0)p.push(...c),h.push({name:n.valuesTo??"value",sources:[...a]});else{let d=new Map,w=new Map,x=ve(n.namesTransform,".value");c.forEach((u,b)=>{let v=u.filter((_,I)=>I!==l),O=JSON.stringify(v),A=d.get(O);if(A===void 0){A=p.length,d.set(O,A),p.push(v);for(let _ of h)_.sources.push(null)}let R=u[l]??null,$=R===null||x===void 0?R:x(R);if($!==null&&typeof $!="string")throw new TypeError(`the transform of \`.value\` must give strings, not ${typeof $}`);let k=$??"NA",T=w.get(k);if(T===void 0&&(T={name:k,sources:p.map(()=>null)},w.set(k,T),h.push(T)),T.sources[A]!==null)throw new RangeError(`the names give the value column '${k}' twice for one key`);T.sources[A]=a[b]})}let N=h.map(d=>Ln(e,d.sources.filter(w=>w!==null))),E=[];if(t==="slowest")for(let d=0;d<p.length;d++)for(let w=0;w<r;w++)E.push([w,d]);else for(let d=0;d<r;d++)for(let w=0;w<p.length;w++)E.push([d,w]);let M=(d,w,x)=>{let u=d.sources[x];return u==null?null:e[u][w]};n.valuesDropNa===!0&&(E=E.filter(([d,w])=>h.some(x=>!W(M(x,d,w)))));let g={},y=E.map(([d])=>d);for(let d of o)a.includes(d)||F(g,d,G(e[d],y));if(s.forEach((d,w)=>{if(w===l)return;let x=ve(n.namesTransform,d),u=b=>{let v=p[b][w<l||l<0?w:w-1];return v===null||x===void 0?v:x(v)};F(g,d,E.map(([,b])=>u(b)))}),h.forEach((d,w)=>{let x=N[w]==="double";if(x&&d.sources.every(u=>u!==null&&e[u]instanceof Float64Array))F(g,d.name,Float64Array.from(E,([u,b])=>M(d,u,b)));else{let u=E.map(([b,v])=>{let O=M(d,b,v);return x&&typeof O=="boolean"?Number(O):O});F(g,d.name,u)}}),n.onWarning!==void 0)for(let d of new Set(f))n.onWarning(d);else le("pivotLonger",f);return g}var oe=e=>typeof e=="number"?"double":typeof e=="string"?"character":"logical";function Yn(e,n){if(e===null||n===null)return e;let t=oe(e);if(t===n)return e;if(n==="double"&&t==="logical")return Number(e);if(n==="logical"&&t==="double"){let r=e;if(Number.isNaN(r))return null;if(r===0||r===1)return r===1;throw new TypeError("Can't convert from `fill` <double> to <logical> due to loss of precision.")}throw new TypeError(`Can't convert \`fill\` <${t}> to <${n}>.`)}var Kn=e=>W(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function $e(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(a,s)=>{let l=JSON.stringify(e.map(i=>Kn(i[s]))),f=t.get(l);return f===void 0&&(f=r.length,t.set(l,f),r.push(s)),f}),firsts:r}}function Wn(e){return W(e)?"NA":typeof e=="number"?Number.isFinite(e)?Y(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function ne(e,n,t){if(e!==void 0)return n(e)?e:Object.hasOwn(e,t)?e[t]:void 0}function zn(e,n={}){S(n,Cn,"pivotWider");let t=Ae("names_vary",n.namesVary),r=Z(e),o=(u,b)=>{let v=[...new Set(te(u))];if(re(e,v),v.length===0)throw new RangeError(`\`${b}\` must select at least one column.`);return v},a=o(n.namesFrom??"name","names_from"),s=o(n.valuesFrom??"value","values_from"),l=n.idCols===void 0?Object.keys(e).filter(u=>!a.includes(u)&&!s.includes(u)):[...new Set(te(n.idCols))];re(e,l);for(let u of l){let b=a.includes(u)?"names_from":s.includes(u)?"values_from":null;if(b!==null)throw new RangeError(`\`id_cols\` can't select a column already selected by \`${b}\`. Column \`${u}\` has already been selected.`)}let f=n.namesPrefix??"",i=n.namesSep??"_",m=$e(l.map(u=>e[u]),r),c=$e(a.map(u=>e[u]),r),p=c.firsts.map((u,b)=>b);n.namesSort===!0&&p.sort((u,b)=>{for(let v of a){let O=fe(e[v][c.firsts[u]],e[v][c.firsts[b]]);if(O!==0)return O}return 0});let h=c.firsts.map(u=>f+a.map(b=>Wn(e[b][u])).join(i)),N=c.firsts.length,E=Array.from({length:m.firsts.length*N},()=>[]);for(let u=0;u<r;u++)E[m.codes[u]*N+c.codes[u]].push(u);let M=u=>typeof u=="function",g=u=>typeof u!="object"||u===null;for(let u of s)if(ne(n.valuesFn,M,u)===void 0&&E.some(b=>b.length>1))throw new RangeError(`values from '${u}' are not uniquely identified; use valuesFn to summarise them`);let y=new Map;for(let u of s){let b=e[u],v=ne(n.valuesFn,M,u),O=new Array(E.length).fill(null),A=null;if(v===void 0)A=Me(u,b),E.forEach(($,k)=>{$.length>0&&(O[k]=b[$[0]])});else{let $=new Uint8Array(E.length),k=0,T=0;for(let _=0;_<r;_++){let I=m.codes[_]*N+c.codes[_];if($[I]===1)continue;$[I]=1,T++;let U=v(E[I].map(Oe=>b[Oe]));if(O[I]=U,U==null)continue;let P=oe(U);if(A===null||A==="logical"&&P==="double")A=P,k=T;else if(P!==A&&(A==="character"||P==="character"))throw new TypeError(`Can't combine \`x[[${k}]]\` <${A}> and \`x[[${T}]]\` <${P}>.`)}}let R=Yn(ne(n.valuesFill,g,u)??null,A);y.set(u,{cells:O,type:A??(R===null?null:oe(R)),fill:R})}let d=(u,b)=>{let v=e[u],{cells:O,type:A,fill:R}=y.get(u),$=m.firsts.map((k,T)=>{let _=T*N+b,I=E[_].length===0?R:O[_];return A==="double"&&typeof I=="boolean"?Number(I):I});return v instanceof Float64Array&&(A==="double"||A===null)?Float64Array.from($,k=>k===null?NaN:k):$},w={};for(let u of l)F(w,u,G(e[u],m.firsts));let x=(u,b)=>s.length===1?h[b]:`${u}${i}${h[b]}`;if(t==="slowest")for(let u of p)for(let b of s)F(w,x(b,u),d(b,u));else for(let u of s)for(let b of p)F(w,x(u,b),d(u,b));return w}export{X as IQR,In as aggregate,de as completeCases,Te as cor,Fe as cov,Ke as cummax,We as cummin,Ye as cumprod,qe as cumsum,tn as cut,Je as cv,ze as diff,Rn as ecdf,rn as findInterval,un as fivenum,Ie as fromRows,Qe as geometricMean,Nn as hist,De as kurtosis,fn as mad,Pe as mean,Ge as meanAD,j as median,Se as merge,Ze as modes,hn as naOmit,qn as pivotLonger,zn as pivotWider,we as pretty,Le as prod,B as quantile,C as range,ke as rank,Xe as scale,z as sd,Be as skewness,Sn as split,_e as subset,Ce as sum,en as table,He as tabulate,kn as tapply,je as toRows,nn as unique,Ue as variance,Ve as weightedMean};
|
|
@@ -11,6 +11,11 @@ import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
|
|
|
11
11
|
import { ddAdd, ddLog, ddMulNum, ddSub, twoSum } from "../special/dd.js";
|
|
12
12
|
import { ddExp } from "../internal/ddexp.js";
|
|
13
13
|
import { pbeta1, qbeta1 } from "./beta.js";
|
|
14
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
15
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
16
|
+
const DARCSINE_KEYS = ["a", "b", "log"];
|
|
17
|
+
const PARCSINE_KEYS = ["a", "b", "lowerTail", "logP"];
|
|
18
|
+
const QARCSINE_KEYS = ["a", "b", "lowerTail", "logP"];
|
|
14
19
|
const valid = (a, b) => Number.isFinite(a) && Number.isFinite(b) && a < b;
|
|
15
20
|
export function darcsine1(x, a, b, log) {
|
|
16
21
|
if (Number.isNaN(x) || !valid(a, b))
|
|
@@ -19,8 +24,19 @@ export function darcsine1(x, a, b, log) {
|
|
|
19
24
|
return d0(log);
|
|
20
25
|
if (x === a || x === b)
|
|
21
26
|
return Infinity;
|
|
22
|
-
|
|
23
|
-
|
|
27
|
+
// b - a overflows (both finite): the density of X/2 on (a/2, b/2), halved
|
|
28
|
+
if (!Number.isFinite(b - a)) {
|
|
29
|
+
const h = darcsine1(x * 0.5, a * 0.5, b * 0.5, log);
|
|
30
|
+
return log ? h - Math.LN2 : h * 0.5;
|
|
31
|
+
}
|
|
32
|
+
if (!log) {
|
|
33
|
+
// sqrt of each: the product (x - a)(b - x) can over- or underflow. Where pi sqrt(x - a) sqrt(b - x) overflows, divide
|
|
34
|
+
// in two steps (the density at the middle of (0, 1.7e308) was 0, not 3.7e-309)
|
|
35
|
+
const sa = Math.sqrt(x - a);
|
|
36
|
+
const sb = Math.sqrt(b - x);
|
|
37
|
+
const den = Math.PI * sa * sb;
|
|
38
|
+
return Number.isFinite(den) ? 1 / den : 1 / (Math.PI * sa) / sb;
|
|
39
|
+
}
|
|
24
40
|
// -log(pi) - (log(x - a) + log(b - x)) / 2 in double-double from the exact differences (the log of a density near 1
|
|
25
41
|
// would turn its rounding into a large relative error)
|
|
26
42
|
const l = ddAdd(ddLog(twoSum(x, -a)), ddLog(twoSum(b, -x)));
|
|
@@ -40,6 +56,9 @@ export function parcsine1(q, a, b, lowerTail, logP) {
|
|
|
40
56
|
return dt0(lowerTail, logP);
|
|
41
57
|
if (q >= b)
|
|
42
58
|
return dt1(lowerTail, logP);
|
|
59
|
+
// b - a overflows (both finite): the same probability on the halved scale (parcsine(0, -1e308, 1e308) was 0, not 1/2)
|
|
60
|
+
if (!Number.isFinite(b - a))
|
|
61
|
+
return parcsine1(q * 0.5, a * 0.5, b * 0.5, lowerTail, logP);
|
|
43
62
|
const w = b - a;
|
|
44
63
|
const nearA = q - a <= b - q;
|
|
45
64
|
// distance to the nearer end, and the tail on that side
|
|
@@ -65,6 +84,9 @@ export function qarcsine1(p, a, b, lowerTail, logP) {
|
|
|
65
84
|
const bd = quantileBoundaries(p, a, b, lowerTail, logP);
|
|
66
85
|
if (bd !== undefined)
|
|
67
86
|
return bd;
|
|
87
|
+
// b - a overflows (both finite): twice the quantile on the halved scale (qarcsine(0.5, -1e308, 1e308) was Inf, not 0)
|
|
88
|
+
if (!Number.isFinite(b - a))
|
|
89
|
+
return 2 * qarcsine1(p, a * 0.5, b * 0.5, lowerTail, logP);
|
|
68
90
|
// Where the lower or upper probability is below e^-40, the distance to that end is w sin^2(pi p / 2) = w (pi p / 2)^2
|
|
69
91
|
// (1 - O(p^2)), from logs (sin^2 underflowed: qarcsine(1.7e-208, 0, 2.6e187) was 0, not 1.9e-228). The log of a
|
|
70
92
|
// tiny probability in double-double from its linear value (log p rounded loses eps |log p| relative); 1 - p is exact
|
|
@@ -111,6 +133,7 @@ export function qarcsine1(p, a, b, lowerTail, logP) {
|
|
|
111
133
|
* @category Distributions
|
|
112
134
|
*/
|
|
113
135
|
export function darcsine(x, options = {}) {
|
|
136
|
+
checkOptions(options, DARCSINE_KEYS, "darcsine"); // generated: option-keys.mjs
|
|
114
137
|
const { a = 0, b = 1, log = false } = options;
|
|
115
138
|
return vectorize(x, (v) => darcsine1(v, a, b, log));
|
|
116
139
|
}
|
|
@@ -127,6 +150,7 @@ export function darcsine(x, options = {}) {
|
|
|
127
150
|
* @category Distributions
|
|
128
151
|
*/
|
|
129
152
|
export function parcsine(q, options = {}) {
|
|
153
|
+
checkOptions(options, PARCSINE_KEYS, "parcsine"); // generated: option-keys.mjs
|
|
130
154
|
const { a = 0, b = 1, lowerTail = true, logP = false } = options;
|
|
131
155
|
return vectorize(q, (v) => parcsine1(v, a, b, lowerTail, logP));
|
|
132
156
|
}
|
|
@@ -143,6 +167,7 @@ export function parcsine(q, options = {}) {
|
|
|
143
167
|
* @category Distributions
|
|
144
168
|
*/
|
|
145
169
|
export function qarcsine(p, options = {}) {
|
|
170
|
+
checkOptions(options, QARCSINE_KEYS, "qarcsine"); // generated: option-keys.mjs
|
|
146
171
|
const { a = 0, b = 1, lowerTail = true, logP = false } = options;
|
|
147
172
|
return vectorize(p, (v) => qarcsine1(v, a, b, lowerTail, logP));
|
|
148
173
|
}
|
|
@@ -14,6 +14,12 @@ import { ddAdd, ddLog, ddMul, ddNeg, twoSum } from "../special/dd.js";
|
|
|
14
14
|
import { dnbeta1, pnbeta1, qnbeta1 } from "./nbeta.js";
|
|
15
15
|
import { qnorm } from "./normal.js";
|
|
16
16
|
import { qgammaStd } from "./gamma.js";
|
|
17
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
18
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
19
|
+
const DBETA_KEYS = ["log", "ncp"];
|
|
20
|
+
const PBETA_KEYS = ["lowerTail", "logP", "ncp"];
|
|
21
|
+
const QBETA_KEYS = ["lowerTail", "logP", "ncp"];
|
|
22
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
17
23
|
/** Form x and 1 - x as a double-double pair based on the smaller of the two (no rounding of 1 - x brought in) */
|
|
18
24
|
function pair(x) {
|
|
19
25
|
return x <= 0.5 ? [[x, 0], twoSum(1, -x)] : [twoSum(1, -(1 - x)), [1 - x, 0]];
|
|
@@ -30,13 +36,26 @@ function dbetaCore(x, a, b, log) {
|
|
|
30
36
|
const l = dbetaDirectLog(xd, xcd, a, b);
|
|
31
37
|
return log ? l : Math.exp(l);
|
|
32
38
|
}
|
|
33
|
-
|
|
39
|
+
// a + b overflows (both shapes near the largest double): the deviances are homogeneous, bd0(cx, cM) = c bd0(x, M), so
|
|
40
|
+
// E is twice that of the halved shapes (the stirlerr terms, about 1/(12 a), are below 1e-308 there). The density was 0
|
|
41
|
+
// where it is 1.1e154: dbeta(0.5, 1e308, 1e308)
|
|
42
|
+
const sumOverflows = !Number.isFinite(a + b);
|
|
43
|
+
let e;
|
|
44
|
+
if (sumOverflows) {
|
|
45
|
+
const h = dbinomExponent(a * 0.5, b * 0.5, xd, xcd).e;
|
|
46
|
+
e = h[0] === Infinity ? h : [2 * h[0], 2 * h[1]];
|
|
47
|
+
}
|
|
48
|
+
else
|
|
49
|
+
e = dbinomExponent(a, b, xd, xcd).e;
|
|
34
50
|
// (a deviance beyond the doubles, from a shape near the largest double: the density is 0, where the double-double sums
|
|
35
51
|
// below were NaN: dbeta(0.998, 55.1, 6.3e307))
|
|
36
52
|
if (e[0] === Infinity)
|
|
37
53
|
return d0(log);
|
|
38
54
|
// With m = ab/(a+b), log(denom)/2 = log(2 pi m)/2 and log(ab/(a+b)) - log(denom)/2 = log(m/(2 pi))/2
|
|
39
|
-
const
|
|
55
|
+
const lo = Math.min(a, b);
|
|
56
|
+
const hi = Math.max(a, b);
|
|
57
|
+
const m = sumOverflows ? lo / (1 + lo / hi) : (a * b) / (a + b);
|
|
58
|
+
const logSum = sumOverflows ? Math.log(hi) + Math.log1p(lo / hi) : Math.log(a + b);
|
|
40
59
|
if (!log && e[0] < 700 && x > 1e-290 && xcd[0] > 1e-290) {
|
|
41
60
|
// f = exp(-E) sqrt(m/(2 pi)) / (x (1 - x)) on the linear scale: no logarithms are needed, and the factors after
|
|
42
61
|
// exp(-E) cost a few roundings whatever the size of log x (in the log form, log x near -700 alone would carry
|
|
@@ -52,7 +71,7 @@ function dbetaCore(x, a, b, log) {
|
|
|
52
71
|
const lxx = x > 1e-290 && xcd[0] > 1e-290 ? ddLog(ddMul(xd, xcd)) : ddAdd(ddLog(xd), ddLog(xcd));
|
|
53
72
|
const lc = m > 1e-290 && m < 1e290
|
|
54
73
|
? 0.5 * Math.log(m / (2 * Math.PI))
|
|
55
|
-
: 0.5 * (Math.log(a) + Math.log(b) -
|
|
74
|
+
: 0.5 * (Math.log(a) + Math.log(b) - logSum - Math.log(2 * Math.PI));
|
|
56
75
|
const t = ddAdd(ddNeg(ddAdd(e, lxx)), [lc, 0]);
|
|
57
76
|
return log ? t[0] + t[1] : Math.exp(t[0]) * (1 + t[1]);
|
|
58
77
|
}
|
|
@@ -129,7 +148,11 @@ export function pbeta1(q, a, b, lowerTail, logP) {
|
|
|
129
148
|
return NaN;
|
|
130
149
|
if (q >= 1)
|
|
131
150
|
return dt1(lowerTail, logP);
|
|
132
|
-
//
|
|
151
|
+
// Nothing lies left of the support, point masses at 0 included (R checks the point masses before q <= 0, so that
|
|
152
|
+
// pbeta(-1, 0, 2) was 1 and pbeta(-1, 0, 0) 0.5); at q = 0 the masses at 0 count
|
|
153
|
+
if (q < 0)
|
|
154
|
+
return dt0(lowerTail, logP);
|
|
155
|
+
// Point masses when a parameter is 0 or infinite
|
|
133
156
|
if (a === 0 || b === 0 || !Number.isFinite(a) || !Number.isFinite(b)) {
|
|
134
157
|
if (a === 0 && b === 0)
|
|
135
158
|
return logP ? -Math.LN2 : 0.5; // 1/2 each at 0 and 1
|
|
@@ -276,6 +299,9 @@ export function qbeta1(p, a, b, lowerTail, logP) {
|
|
|
276
299
|
// Decide whether the answer lies left or right of 1/2 by comparing with the distribution function at x = 1/2
|
|
277
300
|
// (for skewed distributions the answer can be near 0 even when the lower probability exceeds 1/2)
|
|
278
301
|
const atHalf = betaInc(a, b, 0.5, 0.5, lower, true);
|
|
302
|
+
// (a NaN would send the search to the right half and return a wrong value)
|
|
303
|
+
if (Number.isNaN(atHalf))
|
|
304
|
+
return NaN;
|
|
279
305
|
const leftHalf = lower ? logTarget <= atHalf : logTarget >= atHalf;
|
|
280
306
|
if (leftHalf)
|
|
281
307
|
return solveLeftHalf(a, b, lower, logTarget, linearTarget);
|
|
@@ -308,6 +334,7 @@ export function qbeta1(p, a, b, lowerTail, logP) {
|
|
|
308
334
|
* @category Distributions
|
|
309
335
|
*/
|
|
310
336
|
export function dbeta(x, shape1, shape2, options = {}) {
|
|
337
|
+
checkOptions(options, DBETA_KEYS, "dbeta"); // generated: option-keys.mjs
|
|
311
338
|
const { log = false, ncp } = options;
|
|
312
339
|
if (ncp !== undefined)
|
|
313
340
|
return vectorize(x, (v) => dnbeta1(v, shape1, shape2, ncp, log));
|
|
@@ -332,6 +359,7 @@ export function dbeta(x, shape1, shape2, options = {}) {
|
|
|
332
359
|
* @category Distributions
|
|
333
360
|
*/
|
|
334
361
|
export function pbeta(q, shape1, shape2, options = {}) {
|
|
362
|
+
checkOptions(options, PBETA_KEYS, "pbeta"); // generated: option-keys.mjs
|
|
335
363
|
const { lowerTail = true, logP = false, ncp } = options;
|
|
336
364
|
if (ncp !== undefined)
|
|
337
365
|
return vectorize(q, (v) => pnbeta1(v, shape1, shape2, ncp, lowerTail, logP));
|
|
@@ -357,6 +385,7 @@ export function pbeta(q, shape1, shape2, options = {}) {
|
|
|
357
385
|
* @category Distributions
|
|
358
386
|
*/
|
|
359
387
|
export function qbeta(p, shape1, shape2, options = {}) {
|
|
388
|
+
checkOptions(options, QBETA_KEYS, "qbeta"); // generated: option-keys.mjs
|
|
360
389
|
const { lowerTail = true, logP = false, ncp } = options;
|
|
361
390
|
if (ncp !== undefined)
|
|
362
391
|
return vectorize(p, (v) => qnbeta1(v, shape1, shape2, ncp, lowerTail, logP));
|
|
@@ -9,8 +9,16 @@ import { discreteQuantile } from "../internal/discrete.js";
|
|
|
9
9
|
import { betaInc } from "../special/incbet.js";
|
|
10
10
|
import { dbinomRawDD } from "../special/loader.js";
|
|
11
11
|
import { twoSum } from "../special/dd.js";
|
|
12
|
+
import { logAddExp, logSubExp } from "../internal/ddexp.js";
|
|
12
13
|
import { qnorm } from "./normal.js";
|
|
13
14
|
import { nonInteger } from "./poisson.js";
|
|
15
|
+
import { countAtMost, roundHalfEven } from "../internal/integer.js";
|
|
16
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
17
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
18
|
+
const DBINOM_KEYS = ["log"];
|
|
19
|
+
const PBINOM_KEYS = ["lowerTail", "logP"];
|
|
20
|
+
const QBINOM_KEYS = ["lowerTail", "logP"];
|
|
21
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
14
22
|
function badParams(size, prob) {
|
|
15
23
|
return nonInteger(size) || size < 0 || !Number.isFinite(size) || prob < 0 || prob > 1;
|
|
16
24
|
}
|
|
@@ -31,12 +39,37 @@ export function dbinom1(x, size, prob, log) {
|
|
|
31
39
|
return d0(log);
|
|
32
40
|
const pd = prob <= 0.5 ? [prob, 0] : twoSum(1, -(1 - prob));
|
|
33
41
|
const qd = prob <= 0.5 ? twoSum(1, -prob) : [1 - prob, 0];
|
|
34
|
-
return dbinomRawDD(xr, n - xr, pd, qd, log);
|
|
42
|
+
return dbinomRawDD(xr, n - xr, pd, qd, log, n);
|
|
35
43
|
}
|
|
36
44
|
/** P[X <= x] (lower) / P[X > x] (!lower). x an integer, 0 <= x < n */
|
|
37
45
|
function pbinomRaw(x, n, prob, lower, log) {
|
|
38
46
|
// P[X <= x] = 1 - I_p(x + 1, n - x)
|
|
39
|
-
|
|
47
|
+
if (x + 1 - x === 1)
|
|
48
|
+
return betaInc(x + 1, n - x, prob, 1 - prob, !lower, log);
|
|
49
|
+
// Beyond 2^53, x + 1 rounds (to x, or up to x + 2) (pbinom(1e16, 2e16, 0.5) was 0.5, the symmetric I_p(x, x); R too). Without x + 1:
|
|
50
|
+
// I_p(x + 1, n - x) = I_p(x, n - x) - (n - x)/n dbinom(x; n, p). With n - x itself rounded, no parameters are right
|
|
51
|
+
const [b, err] = twoSum(n, -x);
|
|
52
|
+
if (err !== 0)
|
|
53
|
+
return NaN;
|
|
54
|
+
let v;
|
|
55
|
+
let term;
|
|
56
|
+
if (!log) {
|
|
57
|
+
const t = betaInc(x, b, prob, 1 - prob, !lower, false);
|
|
58
|
+
term = (b / n) * dbinom1(x, n, prob, false);
|
|
59
|
+
v = lower ? t + term : t - term;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
const lt = betaInc(x, b, prob, 1 - prob, !lower, true);
|
|
63
|
+
term = Math.log(b / n) + dbinom1(x, n, prob, true);
|
|
64
|
+
v = lower ? logAddExp(lt, term) : logSubExp(lt, term);
|
|
65
|
+
}
|
|
66
|
+
if (Number.isNaN(term))
|
|
67
|
+
return NaN;
|
|
68
|
+
// The upper tail as a difference: where the term is not resolved against it (deep tails, where both logs round to the
|
|
69
|
+
// same value), one unit of x is below the resolution of the result, and the rounded x + 1 serves (round 55)
|
|
70
|
+
if (lower || (log ? Number.isFinite(v) : v > 0))
|
|
71
|
+
return v;
|
|
72
|
+
return betaInc(x + 1, b, prob, 1 - prob, !lower, log);
|
|
40
73
|
}
|
|
41
74
|
export function pbinom1(q, size, prob, lowerTail, logP) {
|
|
42
75
|
if (Number.isNaN(q) || Number.isNaN(size) || Number.isNaN(prob))
|
|
@@ -46,7 +79,7 @@ export function pbinom1(q, size, prob, lowerTail, logP) {
|
|
|
46
79
|
const n = Math.round(size);
|
|
47
80
|
if (q < 0)
|
|
48
81
|
return dt0(lowerTail, logP);
|
|
49
|
-
const x =
|
|
82
|
+
const x = countAtMost(q);
|
|
50
83
|
if (n <= x)
|
|
51
84
|
return dt1(lowerTail, logP);
|
|
52
85
|
if (prob === 0)
|
|
@@ -58,15 +91,16 @@ export function pbinom1(q, size, prob, lowerTail, logP) {
|
|
|
58
91
|
export function qbinom1(p, size, prob, lowerTail, logP) {
|
|
59
92
|
if (Number.isNaN(p) || Number.isNaN(size) || Number.isNaN(prob))
|
|
60
93
|
return NaN;
|
|
61
|
-
if (!Number.isFinite(size) || !Number.isFinite(prob)
|
|
94
|
+
if (!Number.isFinite(size) || !Number.isFinite(prob))
|
|
62
95
|
return NaN;
|
|
63
|
-
// R
|
|
64
|
-
|
|
96
|
+
// As R (R_forceint), a non-integer size is rounded half to even (10.5 is 10, -0.1 is -0), as in qhyper, qsignrank and
|
|
97
|
+
// qwilcox; dbinom and pbinom give NaN for it, as R
|
|
98
|
+
const n = roundHalfEven(size);
|
|
99
|
+
if (prob < 0 || prob > 1 || n < 0)
|
|
100
|
+
return NaN;
|
|
101
|
+
const b = quantileBoundaries(p, 0, n, lowerTail, logP);
|
|
65
102
|
if (b !== undefined)
|
|
66
103
|
return b;
|
|
67
|
-
if (badParams(size, prob))
|
|
68
|
-
return NaN;
|
|
69
|
-
const n = Math.round(size);
|
|
70
104
|
if (prob === 0 || n === 0)
|
|
71
105
|
return 0;
|
|
72
106
|
if (prob === 1)
|
|
@@ -105,6 +139,7 @@ export function qbinom1(p, size, prob, lowerTail, logP) {
|
|
|
105
139
|
* @category Distributions
|
|
106
140
|
*/
|
|
107
141
|
export function dbinom(x, size, prob, options = {}) {
|
|
142
|
+
checkOptions(options, DBINOM_KEYS, "dbinom"); // generated: option-keys.mjs
|
|
108
143
|
const log = options.log ?? false;
|
|
109
144
|
return vectorize(x, (v) => dbinom1(v, size, prob, log));
|
|
110
145
|
}
|
|
@@ -126,6 +161,7 @@ export function dbinom(x, size, prob, options = {}) {
|
|
|
126
161
|
* @category Distributions
|
|
127
162
|
*/
|
|
128
163
|
export function pbinom(q, size, prob, options = {}) {
|
|
164
|
+
checkOptions(options, PBINOM_KEYS, "pbinom"); // generated: option-keys.mjs
|
|
129
165
|
const { lowerTail = true, logP = false } = options;
|
|
130
166
|
return vectorize(q, (v) => pbinom1(v, size, prob, lowerTail, logP));
|
|
131
167
|
}
|
|
@@ -147,11 +183,7 @@ export function pbinom(q, size, prob, options = {}) {
|
|
|
147
183
|
* @category Distributions
|
|
148
184
|
*/
|
|
149
185
|
export function qbinom(p, size, prob, options = {}) {
|
|
186
|
+
checkOptions(options, QBINOM_KEYS, "qbinom"); // generated: option-keys.mjs
|
|
150
187
|
const { lowerTail = true, logP = false } = options;
|
|
151
188
|
return vectorize(p, (v) => qbinom1(v, size, prob, lowerTail, logP));
|
|
152
189
|
}
|
|
153
|
-
/** Round half to even (0.5 goes to the nearest even number; same as R's nearbyint) */
|
|
154
|
-
function roundHalfEven(x) {
|
|
155
|
-
const r = Math.round(x);
|
|
156
|
-
return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r;
|
|
157
|
-
}
|