@numero-uno-jpn/rstats 0.12.0 → 0.13.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 +56 -0
- package/README.ja.md +14 -14
- package/README.md +13 -13
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/dist/chunks/chunk-22SXZNR6.js +2 -0
- package/dist/chunks/chunk-2IAT6MT2.js +2 -0
- package/dist/chunks/chunk-3AKA4KEL.js +3 -0
- package/dist/chunks/{chunk-LEIH4U5X.js → chunk-4AQNVF3Z.js} +2 -2
- package/dist/chunks/chunk-4GNJEYXR.js +2 -0
- package/dist/chunks/chunk-AGRKZXLG.js +2 -0
- package/dist/chunks/{chunk-6BH65HGN.js → chunk-BJHBYEEU.js} +1 -1
- package/dist/chunks/chunk-BSOUJPDF.js +2 -0
- package/dist/chunks/{chunk-VQHEOBTM.js → chunk-CQNVEA22.js} +2 -2
- package/dist/chunks/{chunk-XJQKSR52.js → chunk-F44XUHWI.js} +1 -1
- package/dist/chunks/chunk-JGFUZKLJ.js +2 -0
- package/dist/chunks/{chunk-OX3SBG5X.js → chunk-MEMYFTYS.js} +1 -1
- package/dist/chunks/{chunk-EZ2KD5NA.js → chunk-N3FV6H3C.js} +2 -2
- package/dist/chunks/chunk-NRV3BH7I.js +2 -0
- package/dist/chunks/{chunk-UV2MZYDQ.js → chunk-RTWLZPPG.js} +2 -2
- package/dist/chunks/chunk-SLSDFIW2.js +2 -0
- package/dist/chunks/chunk-SVWU5T7C.js +2 -0
- package/dist/chunks/chunk-VG67L3JA.js +3 -0
- package/dist/chunks/chunk-VWGJYRE6.js +2 -0
- package/dist/data/grouping.js +11 -4
- package/dist/descriptive/basic.js +57 -49
- package/dist/descriptive/cov.js +7 -2
- package/dist/descriptive/factanal.d.ts +16 -0
- package/dist/descriptive/factanal.js +26 -0
- package/dist/descriptive/hist.d.ts +8 -2
- package/dist/descriptive/hist.js +10 -2
- package/dist/descriptive/quantile.d.ts +8 -3
- package/dist/descriptive/quantile.js +10 -6
- package/dist/descriptive/table.d.ts +7 -5
- package/dist/descriptive/table.js +39 -22
- package/dist/descriptive.js +2 -2
- package/dist/distributions/beta.js +17 -0
- package/dist/distributions/binomial.js +3 -0
- package/dist/distributions/gamma.js +7 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +1 -1
- package/dist/htest/agreement.js +7 -2
- package/dist/htest/groups.js +7 -3
- package/dist/htest/mcnemarTest.js +6 -2
- package/dist/htest/pairwise.js +6 -3
- package/dist/htest/polycor.js +5 -3
- package/dist/htest/tTest.d.ts +3 -2
- package/dist/htest/tTest.js +6 -3
- package/dist/htest/trendTests.js +10 -5
- package/dist/internal/levels.d.ts +11 -0
- package/dist/internal/levels.js +48 -0
- package/dist/internal/summary.d.ts +19 -1
- package/dist/internal/summary.js +69 -8
- package/dist/linalg/balance.d.ts +21 -0
- package/dist/linalg/balance.js +191 -0
- package/dist/linalg/eigen.d.ts +1 -1
- package/dist/linalg/eigen.js +8 -2
- package/dist/linalg/expm.d.ts +1 -11
- package/dist/linalg/expm.js +2 -158
- package/dist/linalg/kappa.d.ts +6 -2
- package/dist/linalg/kappa.js +16 -7
- package/dist/linalg/lu.d.ts +13 -2
- package/dist/linalg/lu.js +17 -3
- package/dist/linalg/qr.d.ts +4 -1
- package/dist/linalg/qr.js +2 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/aovEz.js +6 -4
- package/dist/models/coxph.js +5 -2
- package/dist/models/glm.d.ts +4 -1
- package/dist/models/glmFamily.d.ts +1 -1
- package/dist/models/glmFamily.js +24 -2
- package/dist/models/mauchly.js +2 -1
- package/dist/models/modelFrame.js +2 -1
- package/dist/models/survival.js +5 -1
- package/dist/numerics/integrate.d.ts +1 -1
- package/dist/numerics/integrate.js +13 -3
- package/dist/numerics/interp.d.ts +1 -1
- package/dist/numerics/interp.js +3 -0
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +14 -14
- package/dist/special/beta.js +10 -20
- package/dist/special.js +2 -2
- package/dist/tests.js +12 -12
- package/package.json +1 -1
- package/dist/chunks/chunk-3VMBBQLV.js +0 -3
- package/dist/chunks/chunk-4OKAZJJG.js +0 -3
- package/dist/chunks/chunk-ATC4F4BX.js +0 -2
- package/dist/chunks/chunk-EDH53DXN.js +0 -2
- package/dist/chunks/chunk-GSPOO2G3.js +0 -2
- package/dist/chunks/chunk-K7AZ65H7.js +0 -2
- package/dist/chunks/chunk-SGZQDJRR.js +0 -2
- package/dist/chunks/chunk-UH2N3ZQW.js +0 -2
- package/dist/chunks/chunk-WJQZZYOI.js +0 -2
- package/dist/chunks/chunk-WKEFHOFR.js +0 -2
- package/dist/chunks/chunk-WXC25OPJ.js +0 -2
package/dist/descriptive/cov.js
CHANGED
|
@@ -78,6 +78,9 @@ function compute(x, y, options, correlation) {
|
|
|
78
78
|
}
|
|
79
79
|
else if (u.some(Number.isNaN) || v.some(Number.isNaN))
|
|
80
80
|
return NaN;
|
|
81
|
+
// fewer than 2 observations (for "pairwise.complete.obs", in this pair): NaN, as in R, for every method
|
|
82
|
+
if (u.length < 2)
|
|
83
|
+
return NaN;
|
|
81
84
|
if (method === "kendall") {
|
|
82
85
|
if (correlation)
|
|
83
86
|
return kendall(u, v).tau;
|
|
@@ -88,8 +91,10 @@ function compute(x, y, options, correlation) {
|
|
|
88
91
|
return covariance(u, v);
|
|
89
92
|
};
|
|
90
93
|
const out = px.map((a) => py.map((b) => entry(a, b)));
|
|
91
|
-
// as in R, the correlation matrix of x alone has 1 on the diagonal, whatever the column holds
|
|
92
|
-
|
|
94
|
+
// as in R, the correlation matrix of x alone has 1 on the diagonal, whatever the column holds, unless fewer than 2
|
|
95
|
+
// observations are used (then it is all NaN)
|
|
96
|
+
const used = keepRows === undefined ? n : keepRows.filter(Boolean).length;
|
|
97
|
+
if (correlation && y === undefined && use !== "pairwise.complete.obs" && used >= 2)
|
|
93
98
|
out.forEach((r, i) => (r[i] = 1));
|
|
94
99
|
return (y === undefined ? false : !isMatrix(x) && !isMatrix(y)) ? out[0][0] : out;
|
|
95
100
|
}
|
|
@@ -4,6 +4,12 @@
|
|
|
4
4
|
* @category Agreement, reliability and factor analysis
|
|
5
5
|
*/
|
|
6
6
|
export type FactanalRotation = "varimax" | "promax" | "none";
|
|
7
|
+
/**
|
|
8
|
+
* Factor scores of {@link factanal}
|
|
9
|
+
*
|
|
10
|
+
* @category Agreement, reliability and factor analysis
|
|
11
|
+
*/
|
|
12
|
+
export type FactanalScores = "none" | "regression" | "Bartlett";
|
|
7
13
|
/**
|
|
8
14
|
* Options of {@link factanal}
|
|
9
15
|
*
|
|
@@ -16,6 +22,13 @@ export interface FactanalOptions {
|
|
|
16
22
|
nObs?: number;
|
|
17
23
|
/** Default `"varimax"`. */
|
|
18
24
|
rotation?: FactanalRotation;
|
|
25
|
+
/**
|
|
26
|
+
* Factor scores to compute from the data (R's `scores`): `"none"` (default), `"regression"` (Thomson's,
|
|
27
|
+
* z R^-1 L) or `"Bartlett"` (z W L (L' W L)^-1 with W = diag(1 / uniquenesses)), where z is the data
|
|
28
|
+
* standardised by column (denominator n - 1), R its correlation matrix and L the final loadings. Scores need
|
|
29
|
+
* `x`: with `covmat` they are an error.
|
|
30
|
+
*/
|
|
31
|
+
scores?: FactanalScores;
|
|
19
32
|
/** Settings of the optimisation (part of R's `control` list). */
|
|
20
33
|
control?: {
|
|
21
34
|
/** Lower bound of the uniquenesses. Default 0.005. */
|
|
@@ -34,6 +47,8 @@ export interface FactanalResult {
|
|
|
34
47
|
uniquenesses: number[];
|
|
35
48
|
/** The (rotated) loadings, p rows by `factors` columns, columns sorted by decreasing sum of squares, each column's sum positive */
|
|
36
49
|
loadings: number[][];
|
|
50
|
+
/** The factor scores (with `scores` other than `"none"`): one row per observation, one column per factor */
|
|
51
|
+
scores?: number[][];
|
|
37
52
|
/** The rotation matrix (absent for `rotation: "none"` and for one factor) */
|
|
38
53
|
rotmat?: number[][];
|
|
39
54
|
/** The likelihood-ratio statistic (NaN without n.obs or with no degrees of freedom) */
|
|
@@ -69,6 +84,7 @@ export declare function varimax(L: readonly (readonly number[])[]): {
|
|
|
69
84
|
* const fa = factanal(null, 1, { covmat: R });
|
|
70
85
|
* fa.uniquenesses; // [0.19, 0.36, 0.51]
|
|
71
86
|
* fa.loadings; // [[0.9], [0.8], [0.7]]
|
|
87
|
+
* // Factor scores need the data: factanal(x, 1, { scores: "regression" }).scores (one row per row of x)
|
|
72
88
|
* ```
|
|
73
89
|
*
|
|
74
90
|
* @category Agreement, reliability and factor analysis
|
|
@@ -103,14 +103,21 @@ function promax(L) {
|
|
|
103
103
|
* const fa = factanal(null, 1, { covmat: R });
|
|
104
104
|
* fa.uniquenesses; // [0.19, 0.36, 0.51]
|
|
105
105
|
* fa.loadings; // [[0.9], [0.8], [0.7]]
|
|
106
|
+
* // Factor scores need the data: factanal(x, 1, { scores: "regression" }).scores (one row per row of x)
|
|
106
107
|
* ```
|
|
107
108
|
*
|
|
108
109
|
* @category Agreement, reliability and factor analysis
|
|
109
110
|
*/
|
|
110
111
|
export function factanal(x, factors, options = {}) {
|
|
112
|
+
const scores = options.scores ?? "none";
|
|
113
|
+
if (scores !== "none" && scores !== "regression" && scores !== "Bartlett") {
|
|
114
|
+
throw new RangeError("'arg' should be one of “none”, “regression”, “Bartlett”");
|
|
115
|
+
}
|
|
111
116
|
let cv;
|
|
112
117
|
let nObs;
|
|
113
118
|
if (options.covmat !== undefined) {
|
|
119
|
+
if (scores !== "none")
|
|
120
|
+
throw new RangeError("requested scores without an 'x' matrix");
|
|
114
121
|
cv = options.covmat.map((r) => r.slice());
|
|
115
122
|
nObs = options.nObs ?? NaN;
|
|
116
123
|
}
|
|
@@ -184,7 +191,26 @@ export function factanal(x, factors, options = {}) {
|
|
|
184
191
|
objective: fit.value,
|
|
185
192
|
counts: fit.counts,
|
|
186
193
|
};
|
|
194
|
+
if (scores !== "none")
|
|
195
|
+
out.scores = factorScores(x, S, psi, L, scores);
|
|
187
196
|
if (rotmat !== undefined)
|
|
188
197
|
out.rotmat = rotmat;
|
|
189
198
|
return out;
|
|
190
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Factor scores from the data x standardised by column (z), the correlation matrix S, the uniquenesses psi and the
|
|
202
|
+
* final loadings L: regression (Thomson) z S^-1 L, or Bartlett z W L (L' W L)^-1 with W = diag(1 / psi). No factor
|
|
203
|
+
* covariance enters (none is defined for the varimax and promax rotations)
|
|
204
|
+
*/
|
|
205
|
+
function factorScores(x, S, psi, L, method) {
|
|
206
|
+
const n = x.length;
|
|
207
|
+
const means = x[0].map((_, j) => sumOnce(x.map((r) => r[j])) / n);
|
|
208
|
+
const centred = x.map((r) => r.map((v, j) => v - means[j]));
|
|
209
|
+
const sds = colSumsOf(centred, (v) => v * v).map((s) => Math.sqrt(s / (n - 1)));
|
|
210
|
+
const z = centred.map((r) => r.map((v, j) => v / sds[j]));
|
|
211
|
+
if (method === "regression")
|
|
212
|
+
return matMul(z, solve(S, L));
|
|
213
|
+
const WL = L.map((r, i) => r.map((v) => v / psi[i]));
|
|
214
|
+
// (L' W L)^-1 is symmetric, so W L (L' W L)^-1 is the transpose of solve(L' W L, (W L)')
|
|
215
|
+
return matMul(z, transpose(solve(matMul(transpose(L), WL), transpose(WL))));
|
|
216
|
+
}
|
|
@@ -5,9 +5,15 @@ import type { Sample } from "../htest/types.js";
|
|
|
5
5
|
* @category Descriptive statistics
|
|
6
6
|
*/
|
|
7
7
|
export interface PrettyOptions {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* Desired number of intervals. Default `5`. Truncated towards 0 to an integer (as in R); `NaN`, a negative value
|
|
10
|
+
* or one of 2^31 or more in absolute value is an error (unless `x` has no finite values).
|
|
11
|
+
*/
|
|
9
12
|
n?: number;
|
|
10
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* Minimal number of intervals. Default `n / 3` rounded down (computed from `n` before it is truncated). Truncated
|
|
15
|
+
* towards 0 to an integer (as in R); `NaN`, a negative value or one greater than `n` is an error.
|
|
16
|
+
*/
|
|
11
17
|
minN?: number;
|
|
12
18
|
/** Factor applied to the cell when the range is very small. Default `0.75`. */
|
|
13
19
|
shrinkSml?: number;
|
package/dist/descriptive/hist.js
CHANGED
|
@@ -26,8 +26,16 @@ export function pretty(x, options = {}) {
|
|
|
26
26
|
const finite = Array.from(x).filter(Number.isFinite);
|
|
27
27
|
if (finite.length === 0)
|
|
28
28
|
return [];
|
|
29
|
-
|
|
30
|
-
const
|
|
29
|
+
// R converts n and minN to integers (truncating towards 0) and checks them in this order
|
|
30
|
+
const nGiven = options.n ?? 5;
|
|
31
|
+
if (Number.isNaN(nGiven) || Math.abs(nGiven) >= 2 ** 31 || Math.trunc(nGiven) < 0)
|
|
32
|
+
throw new RangeError("invalid 'n' argument");
|
|
33
|
+
const n = Math.trunc(nGiven);
|
|
34
|
+
const minNGiven = options.minN ?? Math.floor(nGiven / 3);
|
|
35
|
+
if (Number.isNaN(minNGiven) || Math.trunc(minNGiven) < 0 || Math.trunc(minNGiven) > n) {
|
|
36
|
+
throw new RangeError("invalid 'min.n' argument");
|
|
37
|
+
}
|
|
38
|
+
const minN = Math.trunc(minNGiven);
|
|
31
39
|
const shrink = options.shrinkSml ?? 0.75;
|
|
32
40
|
const h = options.highUBias ?? 1.5;
|
|
33
41
|
const h5 = options.u5Bias ?? 0.5 + 1.5 * h;
|
|
@@ -55,13 +55,18 @@ export declare function fivenum(x: Sample): [number, number, number, number, num
|
|
|
55
55
|
* @category Descriptive statistics
|
|
56
56
|
*/
|
|
57
57
|
export interface MadOptions extends NaRmOptions {
|
|
58
|
-
/** Centre. Default: the median. */
|
|
58
|
+
/** Centre. Default: the median (`NaN` if `x` has a missing value and `naRm` is not set). */
|
|
59
59
|
center?: number;
|
|
60
60
|
/** Scale factor. Default `1.4826` (consistent for the normal standard deviation). */
|
|
61
61
|
constant?: number;
|
|
62
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* For an even count n, take the lower of the two middle absolute deviations (the "lo-median"): the (n / 2)-th
|
|
64
|
+
* smallest. As in R, n counts the missing values unless `naRm` removed them, the k-th smallest is taken among
|
|
65
|
+
* the deviations that are not missing, and fewer than k of them (or k = 0) is an error. With an odd count the
|
|
66
|
+
* ordinary median is used.
|
|
67
|
+
*/
|
|
63
68
|
low?: boolean;
|
|
64
|
-
/** For an even count, take the higher one (the "hi-median"). */
|
|
69
|
+
/** For an even count n, take the higher one (the "hi-median"): the (n / 2 + 1)-th smallest, as for `low`. Both `low` and `high` is an error for an even count. */
|
|
65
70
|
high?: boolean;
|
|
66
71
|
}
|
|
67
72
|
/**
|
|
@@ -129,20 +129,24 @@ export function fivenum(x) {
|
|
|
129
129
|
* @category Descriptive statistics
|
|
130
130
|
*/
|
|
131
131
|
export function mad(x, options = {}) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const
|
|
132
|
+
// Missing values stay in (and count in n) unless naRm removes them, as in R
|
|
133
|
+
const given = Array.from(x);
|
|
134
|
+
const xs = given.filter((v) => !Number.isNaN(v));
|
|
135
|
+
const all = options.naRm ? xs : given;
|
|
136
|
+
const center = options.center ?? (all.length > xs.length ? NaN : median(xs));
|
|
136
137
|
const constant = options.constant ?? 1.4826;
|
|
137
138
|
const low = options.low ?? false;
|
|
138
139
|
const high = options.high ?? false;
|
|
139
|
-
const dev =
|
|
140
|
+
const dev = all.map((v) => Math.abs(v - center));
|
|
140
141
|
const n = dev.length;
|
|
141
142
|
if ((low || high) && n % 2 === 0) {
|
|
142
143
|
if (low && high)
|
|
143
144
|
throw new RangeError("'low' and 'high' cannot be both TRUE");
|
|
145
|
+
// The k-th smallest among the deviations that are not missing (R's partial sort drops the missing ones)
|
|
144
146
|
const k = n / 2 + (high ? 1 : 0);
|
|
145
|
-
const s = dev.sort((a, b) => a - b);
|
|
147
|
+
const s = dev.filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
|
|
148
|
+
if (k === 0 || s.length < k)
|
|
149
|
+
throw new RangeError(`'partial' index ${k} outside bounds`);
|
|
146
150
|
return constant * s[k - 1];
|
|
147
151
|
}
|
|
148
152
|
return constant * median(dev);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Sample } from "../htest/types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others and NaN are not counted).
|
|
4
|
-
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin).
|
|
4
|
+
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin) and is truncated towards 0, as R does.
|
|
5
5
|
*
|
|
6
6
|
* @example
|
|
7
7
|
* ```ts
|
|
@@ -23,7 +23,8 @@ export interface TableOptions {
|
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
25
|
* Frequency table of the distinct values. Equivalent to R's `table()`. For one numeric vector: `values` in increasing
|
|
26
|
-
* order (NaN last when counted) with their `counts`.
|
|
26
|
+
* order (NaN last when counted) with their `counts`. As in R, values with the same text (15 significant digits, as
|
|
27
|
+
* R's `as.character`) are counted as one, under the smallest of them.
|
|
27
28
|
*
|
|
28
29
|
* @example
|
|
29
30
|
* ```ts
|
|
@@ -63,8 +64,9 @@ export interface CutOptions {
|
|
|
63
64
|
/**
|
|
64
65
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
65
66
|
*
|
|
66
|
-
* @param breaks The break points
|
|
67
|
-
* widened by 1/1000 of the range at
|
|
67
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left give NaN codes), or a
|
|
68
|
+
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
69
|
+
* each end, as R does. That range must be finite.
|
|
68
70
|
*
|
|
69
71
|
* @example
|
|
70
72
|
* ```ts
|
|
@@ -83,7 +85,7 @@ export declare function cut(x: Sample, breaks: number | readonly number[], optio
|
|
|
83
85
|
export interface FindIntervalOptions {
|
|
84
86
|
/** Treat the last interval as closed on the right (with `leftOpen`, the first as closed on the left). */
|
|
85
87
|
rightmostClosed?: boolean;
|
|
86
|
-
/**
|
|
88
|
+
/** Give 1 instead of 0 left of the first point and N - 1 instead of N at or right of the last (N = `vec.length`). */
|
|
87
89
|
allInside?: boolean;
|
|
88
90
|
/** Intervals (v_i, v_(i+1)] instead of [v_i, v_(i+1)). */
|
|
89
91
|
leftOpen?: boolean;
|
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
//
|
|
3
3
|
// Written for rStats.js. cut's generation of breaks from a number of intervals follows R's behaviour: equal spacing
|
|
4
4
|
// over the range, ends widened by 1/1000 of the range, and a special case for a zero range. NaN stands for R's NA:
|
|
5
|
-
// unique keeps one NaN; table counts it according to `useNA`; cut and findInterval return NaN for it.
|
|
5
|
+
// unique keeps one NaN; table counts it according to `useNA`; cut and findInterval return NaN for it. table's levels
|
|
6
|
+
// are made as R's factor() makes them: numbers with the same 15-digit text are one level (src/internal/levels.ts).
|
|
7
|
+
import { numberLevels } from "../internal/levels.js";
|
|
6
8
|
import { seqLength } from "../internal/seq.js";
|
|
7
9
|
/**
|
|
8
10
|
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others and NaN are not counted).
|
|
9
|
-
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin).
|
|
11
|
+
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin) and is truncated towards 0, as R does.
|
|
10
12
|
*
|
|
11
13
|
* @example
|
|
12
14
|
* ```ts
|
|
@@ -18,7 +20,15 @@ import { seqLength } from "../internal/seq.js";
|
|
|
18
20
|
*/
|
|
19
21
|
export function tabulate(bin, nbins) {
|
|
20
22
|
const b = Array.from(bin).map((v) => Math.trunc(v));
|
|
21
|
-
|
|
23
|
+
if (nbins !== undefined) {
|
|
24
|
+
if (Number.isNaN(nbins))
|
|
25
|
+
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
26
|
+
if (Math.trunc(nbins) < 0)
|
|
27
|
+
throw new RangeError("invalid 'nbin' argument");
|
|
28
|
+
if (Math.trunc(nbins) >= 2 ** 31)
|
|
29
|
+
throw new RangeError("attempt to make a table with >= 2^31 elements");
|
|
30
|
+
}
|
|
31
|
+
const nb = nbins === undefined ? Math.max(1, ...b.filter((v) => !Number.isNaN(v))) : Math.trunc(nbins);
|
|
22
32
|
const out = new Array(Math.max(0, nb)).fill(0);
|
|
23
33
|
for (const v of b)
|
|
24
34
|
if (v >= 1 && v <= nb)
|
|
@@ -27,7 +37,8 @@ export function tabulate(bin, nbins) {
|
|
|
27
37
|
}
|
|
28
38
|
/**
|
|
29
39
|
* Frequency table of the distinct values. Equivalent to R's `table()`. For one numeric vector: `values` in increasing
|
|
30
|
-
* order (NaN last when counted) with their `counts`.
|
|
40
|
+
* order (NaN last when counted) with their `counts`. As in R, values with the same text (15 significant digits, as
|
|
41
|
+
* R's `as.character`) are counted as one, under the smallest of them.
|
|
31
42
|
*
|
|
32
43
|
* @example
|
|
33
44
|
* ```ts
|
|
@@ -38,14 +49,14 @@ export function tabulate(bin, nbins) {
|
|
|
38
49
|
*/
|
|
39
50
|
export function table(x, options = {}) {
|
|
40
51
|
const useNA = options.useNA ?? "no";
|
|
41
|
-
const xs = Array.from(x);
|
|
52
|
+
const xs = numberLevels(Array.from(x));
|
|
42
53
|
const map = new Map();
|
|
43
54
|
let nas = 0;
|
|
44
55
|
for (const v of xs) {
|
|
45
56
|
if (Number.isNaN(v))
|
|
46
57
|
nas++;
|
|
47
58
|
else
|
|
48
|
-
map.set(v
|
|
59
|
+
map.set(v, (map.get(v) ?? 0) + 1);
|
|
49
60
|
}
|
|
50
61
|
const values = Array.from(map.keys()).sort((a, b) => a - b);
|
|
51
62
|
const counts = values.map((v) => map.get(v));
|
|
@@ -80,8 +91,9 @@ export function unique(x) {
|
|
|
80
91
|
/**
|
|
81
92
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
82
93
|
*
|
|
83
|
-
* @param breaks The break points
|
|
84
|
-
* widened by 1/1000 of the range at
|
|
94
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left give NaN codes), or a
|
|
95
|
+
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
96
|
+
* each end, as R does. That range must be finite.
|
|
85
97
|
*
|
|
86
98
|
* @example
|
|
87
99
|
* ```ts
|
|
@@ -101,9 +113,16 @@ export function cut(x, breaks, options = {}) {
|
|
|
101
113
|
if (!(k >= 2))
|
|
102
114
|
throw new RangeError("invalid number of intervals");
|
|
103
115
|
const nb = Math.trunc(k + 1);
|
|
104
|
-
const
|
|
105
|
-
const lo = Math.min(...
|
|
106
|
-
const hi = Math.max(...
|
|
116
|
+
const present = xs.filter((v) => !Number.isNaN(v));
|
|
117
|
+
const lo = Math.min(...present);
|
|
118
|
+
const hi = Math.max(...present);
|
|
119
|
+
// R's errors for a range that is not finite: the same infinity everywhere fails before the checks of the ends
|
|
120
|
+
if (present.length > 0 && lo === hi && !Number.isFinite(lo))
|
|
121
|
+
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
122
|
+
if (present.length === 0 || lo === -Infinity)
|
|
123
|
+
throw new RangeError("'from' must be a finite number");
|
|
124
|
+
if (hi === Infinity)
|
|
125
|
+
throw new RangeError("'to' must be a finite number");
|
|
107
126
|
let dx = hi - lo;
|
|
108
127
|
if (dx === 0) {
|
|
109
128
|
dx = lo !== 0 ? Math.abs(lo) : 1;
|
|
@@ -116,7 +135,7 @@ export function cut(x, breaks, options = {}) {
|
|
|
116
135
|
}
|
|
117
136
|
}
|
|
118
137
|
else
|
|
119
|
-
br =
|
|
138
|
+
br = breaks.filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
|
|
120
139
|
if (new Set(br).size < br.length)
|
|
121
140
|
throw new RangeError("'breaks' are not unique");
|
|
122
141
|
return binCode(xs, br, right, includeLowest);
|
|
@@ -170,6 +189,13 @@ export function findInterval(x, vec, options = {}) {
|
|
|
170
189
|
return Array.from(x).map((v) => {
|
|
171
190
|
if (Number.isNaN(v))
|
|
172
191
|
return NaN;
|
|
192
|
+
if (n === 0)
|
|
193
|
+
return 0;
|
|
194
|
+
// The two ends are separate rules, as in R (with n = 1 the second can give 0 and the first 1)
|
|
195
|
+
if (leftOpen ? v <= vec[0] : v < vec[0])
|
|
196
|
+
return allInside || (rightmostClosed && leftOpen && v === vec[0]) ? 1 : 0;
|
|
197
|
+
if (leftOpen ? v > vec[n - 1] : v >= vec[n - 1])
|
|
198
|
+
return allInside || (rightmostClosed && !leftOpen && v === vec[n - 1]) ? n - 1 : n;
|
|
173
199
|
// count of vec <= v (or < v when left-open)
|
|
174
200
|
let lo = 0;
|
|
175
201
|
let hi = n;
|
|
@@ -180,15 +206,6 @@ export function findInterval(x, vec, options = {}) {
|
|
|
180
206
|
else
|
|
181
207
|
hi = mid;
|
|
182
208
|
}
|
|
183
|
-
|
|
184
|
-
if (rightmostClosed && n > 0) {
|
|
185
|
-
if (!leftOpen && i === n && v === vec[n - 1])
|
|
186
|
-
i = n - 1;
|
|
187
|
-
if (leftOpen && i === 0 && v === vec[0])
|
|
188
|
-
i = 1;
|
|
189
|
-
}
|
|
190
|
-
if (allInside)
|
|
191
|
-
i = Math.min(Math.max(i, 1), n - 1);
|
|
192
|
-
return i;
|
|
209
|
+
return lo;
|
|
193
210
|
});
|
|
194
211
|
}
|
package/dist/descriptive.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.
|
|
2
|
-
import{l as fe,m as me,n as he}from"./chunks/chunk-SGZQDJRR.js";import"./chunks/chunk-EZ2KD5NA.js";import{A as Re,B as Fe,C as je,D as Se,E as Te,F as _e,a as q,b as _,c as V,d as v,e as H,f as pe,g as ge,j as de,k as ye,l as z,m as we,n as be,o as Ne,p as Ee,q as Ae,r as I,s as R,t as j,u as xe,v as Me,w as $e,x as Oe,y as ke,z as ve}from"./chunks/chunk-WXC25OPJ.js";import{a as K,b as Ie,c as Ce,d as Le,e as Pe,f as Ue}from"./chunks/chunk-UH2N3ZQW.js";import"./chunks/chunk-XJQKSR52.js";import"./chunks/chunk-GSPOO2G3.js";import"./chunks/chunk-EDH53DXN.js";import"./chunks/chunk-OX3SBG5X.js";import{b as S,c as J,g as T,h as X}from"./chunks/chunk-4OKAZJJG.js";import{a as G}from"./chunks/chunk-WKEFHOFR.js";var B=4*Number.EPSILON,qe={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function Ve(e,n,t){let r=e.length,o=a=>e[Math.min(Math.max(a,1),r)-1];if(t===7){let a=1+(r-1)*n,g=Math.floor(a),m=o(g),d=o(Math.ceil(a));if(a>g&&d!==m){let b=a-g;return(1-b)*m+b*d}return m}let i,l;if(t<=3){let a=t===3?r*n-.5:r*n;i=Math.floor(a*(1+B)),t===1?l=a>i?1:0:t===2?l=a>i?1:.5:l=a!==i||Math.abs(i%2)===1?1:0}else{let[a,g]=qe[t],m=a+n*(r+1-a-g);i=Math.floor(m*(1+B)),l=m-i,Math.abs(l)<B&&(l=0)}let s=o(i),f=o(i+1);return l===1?f:l>0&&l<1&&s!==f?(1-l)*s+l*f:s}function C(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=z(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let i=o.sort((a,g)=>a-g),l=typeof n=="number"?[n]:Array.from(n),s=100*Number.EPSILON;if(l.some(a=>a<-s||a>1+s))throw new RangeError("'probs' outside [0,1]");let f=l.map(a=>Number.isNaN(a)||i.length===0?NaN:Ve(i,Math.min(Math.max(a,0),1),r));return typeof n=="number"?f[0]:f}function W(e,n={}){let[t,r]=C(e,[.25,.75],n);return r-t}function ze(e){let n=Array.from(e).filter(i=>!Number.isNaN(i)).sort((i,l)=>i-l),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(i=>.5*(n[Math.floor(i)-1]+n[Math.ceil(i)-1]))}function Be(e,n={}){let t=z(e,n.naRm);if(t===void 0)return NaN;let r=n.center??R(t),o=n.constant??1.4826,i=n.low??!1,l=n.high??!1,s=t.map(a=>Math.abs(a-r)),f=s.length;if((i||l)&&f%2===0){if(i&&l)throw new RangeError("'low' and 'high' cannot be both TRUE");let a=f/2+(l?1:0),g=s.sort((m,d)=>m-d);return o*g[a-1]}return o*R(s)}var Y=e=>e===null||typeof e=="number"&&Number.isNaN(e),ee=e=>Array.isArray(e)||ArrayBuffer.isView(e);function We(e){if(ee(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 ne(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(We),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,i)=>r.every(l=>!Y(l[i])))}function Ze(e){if(ee(e))return Array.from(e).filter(r=>!Y(r));let n=ne(e),t={};for(let[r,o]of Object.entries(e)){let i=Array.from(o).filter((l,s)=>n[s]);t[r]=o instanceof Float64Array?Float64Array.from(i):i}return t}function te(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5,o=n.minN??Math.floor(r/3),i=n.shrinkSml??.75,l=n.highUBias??1.5,s=n.u5Bias??.5+1.5*l,f=1/0,a=-1/0;for(let w of t)w<f&&(f=w),w>a&&(a=w);let g=a-f,m,d;if(g===0&&a===0)m=1,d=!0;else{m=Math.max(Math.abs(f),Math.abs(a));let M=(1+(s>=1.5*l+.5?1/(1+l):1.5/(1+s)))*Math.max(1,r)*Number.EPSILON;d=g<m*M*3}d?(m>10&&(m=9+m/10),m*=i,o>1&&(m/=o)):(m=r>1?g/r:g,g===1/0&&r>=2&&(m=a/r-f/r));let b=2**-20*De;m<b?m=b:m>Number.MAX_VALUE/1.25&&(m=Number.MAX_VALUE/1.25);let y=10**Math.floor(Math.log10(m)),x=[[2*y,l],[5*y,s],[10*y,l]],N=y;for(let[w,M]of x)if(w-m<M*(m-N))N=w;else break;let h=1e-10,u=Math.floor(f/N+h);for(;u*N>f+h*N;)u--;for(;!Number.isFinite(u*N);)u++;let c=Math.ceil(a/N-h);for(;c*N<a-h*N;)c++;for(;!Number.isFinite(c*N);)c--;let p=Math.trunc(.5+c-u);if(p<o){let w=o-p,M=Math.floor(w/2),k=w%2;f===0&&u===0&&a!==0?c+=w:a===0&&c===0&&f!==0?u-=w:u>=0?(c+=M,u-=M+k):(u-=M,c+=M+k),p=o}let E=u*N<f?u*N:f,A=c*N>a?c*N:a;if(p<=0)return[E];let $;if(Number.isFinite(A-E))$=K(E,A,p+1);else{let w=A/p-E/p;$=Array.from({length:p+1},(M,k)=>E+k*w),$[p]=A}let O=A/p-E/p;return $.map(w=>Math.abs(w)<1e-14*O?0:w)}var De=22250738585072014e-324;function Qe(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function Je(e,n){let t=e.length,[r,o]=j(e),i=o-r;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let l=3.5*I(e)*t**-.3333333333333333;return l>0?Math.max(1,Math.ceil(i/l)):1}case"fd":case"freedman-diaconis":{let l=e.map(Qe),s=2*W(l);for(let f=1/8;s===0&&f>=1/512;f/=2){let[a,g]=C(l,[f,1-f]);s=(g-a)/(1-2*f)}return s===0&&(s=3.5*I(e)),s>0?Math.ceil(i/s*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?R(t):e.length<=3?n:Math.min(...t.filter(r=>r>0))}function Ge(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,i=n.includeLowest??!0,l=n.breaks??"Sturges",s;if(typeof l!="string"&&typeof l!="number"&&l.length>1)s=[...l].sort((h,u)=>h-u);else{i=!0;let h=typeof l=="string"?Je(t,l):typeof l=="number"?l:l[0];if(!Number.isFinite(h)||h<1)throw new RangeError("invalid number of 'breaks'");h=Math.min(h,1e6);let[u,c]=j(t);s=te([u,c],{n:h,minN:1});for(let p=1;p<s.length;p++)if(!(s[p]-s[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=s.length,[a,g]=r>0?j(t):[0,0],m=1e-7*Xe(s,g-a),d=s.map((h,u)=>o?u===0&&i?h-m:h+m:u<f-1?h-m:i?h+m:h-m),b=new Array(Math.max(0,f-1)).fill(0),y=0;for(let h of t){let u=He(h,d,o,i);u>=0&&(b[u]++,y++)}if(y<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let x=b.map((h,u)=>h/(r*(s[u+1]-s[u]))),N=b.map((h,u)=>.5*(s[u+1]+s[u]));return{breaks:s,counts:b,density:x,mids:N}}function He(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 s=1,f=o;for(;s<f;){let a=s+f>>1;e<=n[a]?f=a:s=a+1}return s-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let i=0,l=o-1;for(;i<l;){let s=i+l+1>>1;n[s]<=e?i=s:l=s-1}return i}function Ke(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,i=t;for(;o<i;){let l=o+i>>1;n[l]<=r?o=l+1:i=l}return o/t}}var L=e=>e===null||typeof e=="number"&&Number.isNaN(e),Ye=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?G(e,n):Number(e)-Number(n),en=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?S(e):e>0?"Inf":"-Inf";function nn(e,n){let t=Array.from(n,s=>s===0?0:s),r=new Set(t.filter(s=>!L(s)).map(s=>typeof s));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 i=[...new Set(t.filter(s=>!L(s)))].sort(Ye),l=new Map(i.map((s,f)=>[s,f]));return{levels:i,codes:t.map(s=>L(s)?-1:l.get(s))}}var F=e=>Array.isArray(e)||e instanceof Float64Array;function le(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(F))return[...e];if(e.some(F))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function Z(e,n,t){e.forEach((l,s)=>{if(l.length!==t)throw new RangeError(`${n[s]} must have one label per row (${t}), not ${l.length}`)});let r=e.map((l,s)=>nn(n[s],l)),o=r.reduce((l,s)=>l*s.levels.length,1),i=new Array(t);for(let l=0;l<t;l++){let s=0,f=1;for(let a of r){let g=a.codes[l];if(g<0){s=-1;break}s+=g*f,f*=a.levels.length}i[l]=s}return{factors:r,size:o,cells:i}}function D(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function ae(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 ie=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function tn(e,n,t){let r=Array.from(e),o=le(n),i=Z(o,ie(o.length,"index"),r.length),l=D(i).map(a=>a.length===0?null:{value:t(a.map(g=>r[g]))}),f=l.every(a=>a===null||typeof a.value=="number")?l.map(a=>a===null?NaN:a.value):l.map(a=>a===null?null:a.value);return{dim:i.factors.map(a=>a.levels.length),dimnames:i.factors.map(a=>[...a.levels]),values:f}}function rn(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=o instanceof Float64Array?Float64Array.from(n,i=>o[i]):n.map(i=>o[i]);return t}function on(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!F(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={}){let r=t.sep??".",o=le(n),i=!F(e);if(i&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let l=i?on(e):e.length,s=Z(o,ie(o.length,"f"),l),f=i?[]:Array.from(e),a=new Map;return D(s).forEach((g,m)=>{if(g.length===0&&(t.drop||s.factors.length===1))return;let d=ae(s,m).map(en).join(r);a.set(d,i?rn(e,g):g.map(b=>f[b]))}),a}function re(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!F(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 oe(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(!F(t))throw new TypeError(`column '${n}' must be an array`);return t}function ln(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}=J(`~ ${e.slice(t+1)}`),i=/^[A-Za-z.][A-Za-z0-9._]*$/,l;if(r!=="."){let a=/^cbind\s*\((.*)\)$/s.exec(r);if(l=a===null?[r]:a[1].split(",").map(g=>g.trim()),l.some(g=>!i.test(g)||g==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(T(o,[]).length<T(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let s=l===void 0?[]:n.filter(a=>!l.includes(a)),f=T(o,s);return X(o,()=>0,s),{values:l??n.filter(a=>!f.includes(a)),groups:f}}function se(e,n,t,r,o,i){let l=r[0]?.length??n[0]?.length??0;e.forEach((m,d)=>{if(n[d].length!==l)throw new RangeError(`variable lengths differ (found for '${m}')`)});let s=Z(r,t,l),f=D(s).map((m,d)=>({cell:d,rows:m.filter(o)})).filter(m=>m.rows.length>0),a={},g=f.map(m=>ae(s,m.cell));return t.forEach((m,d)=>{a[m]=g.map(b=>b[d])}),e.forEach((m,d)=>{let b=n[d],x=f.map(h=>i(h.rows.map(u=>b[u]))).map(h=>{if(typeof h=="number")return{names:void 0,values:[h]};if(Array.isArray(h))return{names:void 0,values:[...h]};let u=h;return{names:Object.keys(u),values:Object.values(u)}}),N=x[0]?.values.length??1;if(x.some(h=>h.values.length!==N))throw new RangeError("fun must return values of the same length for every group");if(N===1&&x[0]?.names===void 0){a[m]=x.map(h=>h.values[0]);return}for(let h=0;h<N;h++){let u=x[0].names?.[h]??String(h+1);a[`${m}.${u}`]=x.map(c=>c.values[h])}}),a}function an(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 s=n,{values:f,groups:a}=ln(e,Object.keys(s)),g=y=>Object.prototype.hasOwnProperty.call(s,y),m=f.map(y=>re(y,g(y)?s[y]:void 0)),d=a.map(y=>oe(s,y));return se(f,m,a,d,y=>m.every(x=>!Number.isNaN(x[y]))&&d.every(x=>!L(x[y])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(s=>re(s,e[s])),i=Object.keys(n);if(i.length===0)throw new RangeError("'by' must name at least one grouping column");let l=i.map(s=>oe(n,s));return se(r,o,i,l,()=>!0,t)}var P=e=>typeof e=="string"?[e]:[...e];function ue(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function cn(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 un(e,n){let t=null;for(let r of n){let o=cn(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 fn(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(i=>{let l=o.exec(i);return Array.from({length:t},(s,f)=>l===null?null:l[f+1]??null)})}function mn(e,n,t,r){let o=new RegExp(n,"g"),i=[],l=[],s=e.map((a,g)=>{let m=[],d=0;for(let b of a.matchAll(o))b[0].length!==0&&(m.push(a.slice(d,b.index)),d=b.index+b[0].length);return m.push(a.slice(d)),m.length>t&&i.push(g+1),m.length<t&&l.push(g+1),Array.from({length:t},(b,y)=>m[y]??null)}),f=a=>`${a.length} rows [${a.join(", ")}]`;return i.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(i)}.`),l.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(l)}.`),s}function hn(e,n,t,r){let{namesSep:o,namesPattern:i}=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(i===void 0)return e.map(s=>[s]);let l=new RegExp(i);return e.map(s=>[l.exec(s)?.[1]??null])}if(o===void 0==(i===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?mn(e,o,n.length,r):fn(e,i,n.length)}function pn(e,n){let t=q(e),r=Object.keys(e),o=typeof n.cols=="function"?r.filter(n.cols):[...new Set(n.cols)];if(ue(e,o),o.length===0)throw new Error("`cols` must select at least one column.");let i=P(n.namesTo??"name"),l=i.indexOf(".value");if(i.lastIndexOf(".value")!==l)throw new Error('`names_to` may contain ".value" only once');let s=[],f=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),a=o.map(u=>f===null?u:u.replace(f,"")),g=hn(a,i,n,s),m=[],d=[];if(l<0)m.push(...g),d.push({name:n.valuesTo??"value",sources:[...o]});else{let u=new Map,c=new Map;g.forEach((p,E)=>{let A=p.filter((k,U)=>U!==l),$=JSON.stringify(A),O=u.get($);if(O===void 0){O=m.length,u.set($,O),m.push(A);for(let k of d)k.sources.push(null)}let w=p[l]??"NA",M=c.get(w);if(M===void 0&&(M={name:w,sources:m.map(()=>null)},c.set(w,M),d.push(M)),M.sources[O]!==null)throw new Error(`the names give the value column '${w}' twice for one key`);M.sources[O]=o[E]})}let b=d.map(u=>un(e,u.sources.filter(c=>c!==null))),y=[];if(n.colsVary==="slowest")for(let u=0;u<m.length;u++)for(let c=0;c<t;c++)y.push([c,u]);else for(let u=0;u<t;u++)for(let c=0;c<m.length;c++)y.push([u,c]);let x=(u,c,p)=>{let E=u.sources[p];return E==null?null:e[E][c]};n.valuesDropNa===!0&&(y=y.filter(([u,c])=>d.some(p=>!_(x(p,u,c)))));let N={},h=y.map(([u])=>u);for(let u of r)o.includes(u)||v(N,u,V(e[u],h));if(i.forEach((u,c)=>{if(c===l)return;let p=n.namesTransform?.[u],E=A=>{let $=m[A][c<l||l<0?c:c-1];return $===null||p===void 0?$:p($)};v(N,u,y.map(([,A])=>E(A)))}),d.forEach((u,c)=>{let p=b[c]==="double";if(p&&u.sources.every(E=>E!==null&&e[E]instanceof Float64Array))v(N,u.name,Float64Array.from(y,([E,A])=>x(u,E,A)));else{let E=y.map(([A,$])=>{let O=x(u,A,$);return p&&typeof O=="boolean"?Number(O):O});v(N,u.name,E)}}),n.onWarning!==void 0)for(let u of new Set(s))n.onWarning(u);return N}var gn=e=>_(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function ce(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(i,l)=>{let s=JSON.stringify(e.map(a=>gn(a[l]))),f=t.get(s);return f===void 0&&(f=r.length,t.set(s,f),r.push(l)),f}),firsts:r}}function dn(e){return _(e)?"NA":typeof e=="number"?Number.isFinite(e)?S(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 yn(e,n={}){let t=q(e),r=P(n.namesFrom??"name"),o=P(n.valuesFrom??"value"),i=n.idCols===void 0?Object.keys(e).filter(c=>!r.includes(c)&&!o.includes(c)):P(n.idCols);ue(e,[...i,...r,...o]);let l=n.namesPrefix??"",s=n.namesSep??"_",f=ce(i.map(c=>e[c]),t),a=ce(r.map(c=>e[c]),t),g=a.firsts.map((c,p)=>p);n.namesSort===!0&&g.sort((c,p)=>{for(let E of r){let A=H(e[E][a.firsts[c]],e[E][a.firsts[p]]);if(A!==0)return A}return 0});let m=a.firsts.map(c=>l+r.map(p=>dn(e[p][c])).join(s)),d=a.firsts.length,b=Array.from({length:f.firsts.length*d},()=>[]);for(let c=0;c<t;c++)b[f.codes[c]*d+a.codes[c]].push(c);let y=c=>typeof c=="function",x=c=>typeof c!="object"||c===null,N=(c,p)=>{let E=e[c],A=Q(n.valuesFn,y,c),$=Q(n.valuesFill,x,c)??null,O=f.firsts.map((w,M)=>{let k=b[M*d+p];return k.length===0?$:A!==void 0?A(k.map(U=>E[U])):E[k[0]]});return E instanceof Float64Array&&O.every(w=>w===null||typeof w=="number")?Float64Array.from(O,w=>w===null?NaN:w):O};for(let c of o)if(Q(n.valuesFn,y,c)===void 0&&b.some(p=>p.length>1))throw new Error(`values from '${c}' are not uniquely identified; use valuesFn to summarise them`);let h={};for(let c of i)v(h,c,V(e[c],f.firsts));let u=(c,p)=>o.length===1?m[p]:`${c}${s}${m[p]}`;if(n.namesVary==="slowest")for(let c of g)for(let p of o)v(h,u(p,c),N(p,c));else for(let c of o)for(let p of g)v(h,u(c,p),N(c,p));return h}export{W as IQR,an as aggregate,ne as completeCases,he as cor,me as cov,$e as cummax,Oe as cummin,Me as cumprod,xe as cumsum,Pe as cut,Te as cv,ke as diff,Ke as ecdf,Ue as findInterval,ze as fivenum,de as fromRows,Fe as geometricMean,Ge as hist,Re as kurtosis,Be as mad,Ne as mean,Se as meanAD,R as median,pe as merge,je as modes,Ze as naOmit,pn as pivotLonger,yn as pivotWider,te as pretty,be as prod,C as quantile,j as range,fe as rank,_e as scale,I as sd,ve as skewness,sn as split,ge as subset,we as sum,Ce as table,Ie as tabulate,tn as tapply,ye as toRows,Le as unique,Ae as variance,Ee as weightedMean};
|
|
1
|
+
/*! rStats.js 0.13.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{l as me,m as he,n as pe}from"./chunks/chunk-NRV3BH7I.js";import"./chunks/chunk-N3FV6H3C.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-SVWU5T7C.js";import{a as ee,b as Le,c as Ce,d as Pe,e as Ue,f as qe}from"./chunks/chunk-2IAT6MT2.js";import"./chunks/chunk-F44XUHWI.js";import"./chunks/chunk-SLSDFIW2.js";import"./chunks/chunk-4GNJEYXR.js";import"./chunks/chunk-MEMYFTYS.js";import{a as G,e as I,f as J}from"./chunks/chunk-BSOUJPDF.js";import{a as H}from"./chunks/chunk-JGFUZKLJ.js";import{b as _,c as X}from"./chunks/chunk-3AKA4KEL.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};
|
|
@@ -47,6 +47,18 @@ function dbetaCore(x, a, b, log) {
|
|
|
47
47
|
const t = ddAdd(ddNeg(ddAdd(e, lxx)), [lc, 0]);
|
|
48
48
|
return log ? t[0] + t[1] : Math.exp(t[0]) * (1 + t[1]);
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Log density when one shape is 1 (0 < x < 1, 0 < a, b < Inf, not both 1). The density is elementary:
|
|
52
|
+
* log f = log(b) + (b - 1) log(1 - x) for a = 1, log f = log(a) + (a - 1) log(x) for b = 1
|
|
53
|
+
* (B(1, b) = 1/b). Evaluated in double-double, with 1 - x exact, so that the result is correctly rounded in practice
|
|
54
|
+
* and exactly 0 where the two terms cancel, as R's (for example Beta(1, 2) at x = 1/2)
|
|
55
|
+
*/
|
|
56
|
+
function dbetaShape1Log(x, a, b) {
|
|
57
|
+
const [xd, xcd] = pair(x);
|
|
58
|
+
const [s, l] = a === 1 ? [b, xcd] : [a, xd];
|
|
59
|
+
const t = ddAdd(ddLog([s, 0]), ddMul(twoSum(s, -1), ddLog(l)));
|
|
60
|
+
return t[0] + t[1];
|
|
61
|
+
}
|
|
50
62
|
/** Log density (0 < x < 1, 0 < a, b < Inf) */
|
|
51
63
|
export function dbetaLog(x, _xc, a, b) {
|
|
52
64
|
return dbetaCore(x, a, b, true);
|
|
@@ -82,6 +94,11 @@ export function dbeta1(x, a, b, log) {
|
|
|
82
94
|
return Infinity;
|
|
83
95
|
return log ? Math.log(a) : a;
|
|
84
96
|
}
|
|
97
|
+
// Beta(1, 1) is uniform: density exactly 1, log density exactly 0 (as in R)
|
|
98
|
+
if (a === 1 && b === 1)
|
|
99
|
+
return log ? 0 : 1;
|
|
100
|
+
if (log && (a === 1 || b === 1))
|
|
101
|
+
return dbetaShape1Log(x, a, b);
|
|
85
102
|
return dbetaCore(x, a, b, log);
|
|
86
103
|
}
|
|
87
104
|
export function pbeta1(q, a, b, lowerTail, logP) {
|
|
@@ -17,6 +17,9 @@ function badParams(size, prob) {
|
|
|
17
17
|
export function dbinom1(x, size, prob, log) {
|
|
18
18
|
if (Number.isNaN(x) || Number.isNaN(size) || Number.isNaN(prob))
|
|
19
19
|
return NaN;
|
|
20
|
+
// size Inf (as in R 4.5; pbinom and qbinom take it as invalid): no mass at any x, except at 0 when prob = 0
|
|
21
|
+
if (size === Infinity && prob >= 0 && prob <= 1)
|
|
22
|
+
return prob === 0 && x === 0 ? (log ? 0 : 1) : d0(log);
|
|
20
23
|
if (badParams(size, prob))
|
|
21
24
|
return NaN;
|
|
22
25
|
if (nonInteger(x) || x < 0 || !Number.isFinite(x))
|
|
@@ -74,6 +74,10 @@ export function pgamma1(q, shape, scale, lowerTail, logP) {
|
|
|
74
74
|
return x;
|
|
75
75
|
if (shape === 0)
|
|
76
76
|
return x <= 0 ? dt0(lowerTail, logP) : dt1(lowerTail, logP);
|
|
77
|
+
// Shape Inf puts all the mass at +Inf. R gives NaN for 0 < x < 1 and these limits elsewhere; the limits are
|
|
78
|
+
// returned for every finite x (docs/differences-from-r.md)
|
|
79
|
+
if (shape === Infinity)
|
|
80
|
+
return x === Infinity ? dt1(lowerTail, logP) : dt0(lowerTail, logP);
|
|
77
81
|
if (x <= 0)
|
|
78
82
|
return dt0(lowerTail, logP);
|
|
79
83
|
return gammaInc(shape, x, lowerTail, logP);
|
|
@@ -132,6 +136,9 @@ export function qgamma1(p, shape, scale, lowerTail, logP) {
|
|
|
132
136
|
return NaN;
|
|
133
137
|
if (shape === 0)
|
|
134
138
|
return 0;
|
|
139
|
+
// Shape Inf: all the mass at +Inf, so every probability strictly between 0 and 1 maps to Inf
|
|
140
|
+
if (shape === Infinity)
|
|
141
|
+
return Infinity;
|
|
135
142
|
return qgammaStd(p, shape, lowerTail, logP) * scale;
|
|
136
143
|
}
|
|
137
144
|
/**
|