@numero-uno-jpn/rstats 0.15.3 → 0.16.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 +166 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +24 -4
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +12 -4
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +5 -0
- package/dist/distributions/f.js +32 -17
- package/dist/distributions/gamma.js +27 -3
- package/dist/distributions/geometric.js +49 -13
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +2 -1
- package/dist/distributions/laplace.js +27 -6
- package/dist/distributions/logistic.js +4 -1
- package/dist/distributions/lognormal.js +8 -2
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +62 -11
- package/dist/distributions/nchisq.js +30 -6
- package/dist/distributions/negbinomial.js +94 -17
- package/dist/distributions/normal.js +9 -4
- package/dist/distributions/nt.js +392 -17
- package/dist/distributions/pareto.js +4 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/triangular.js +10 -5
- package/dist/distributions/tukey.js +5 -2
- package/dist/distributions/weibull.js +10 -0
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- 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/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- 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/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/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -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 +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- 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 +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- 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 +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -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 +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -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/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -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 +17 -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.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- 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-ZIX7NYQF.js +0 -2
|
@@ -4,12 +4,14 @@
|
|
|
4
4
|
// the off-diagonal residuals by L-BFGS-B (this library's optim), the oblique rotation is GPArotation's quartimin
|
|
5
5
|
// with its Barzilai-Borwein step and non-monotone line search, and the general factor comes from a one-factor
|
|
6
6
|
// minres analysis of the factor correlations.
|
|
7
|
+
import { checkCovmat } from "../internal/covmat.js";
|
|
7
8
|
import { eigen } from "../linalg/eigen.js";
|
|
8
9
|
import { solve } from "../linalg/solve.js";
|
|
9
10
|
import { svd } from "../linalg/svd.js";
|
|
10
11
|
import { optim } from "../optim/optim.js";
|
|
11
12
|
import { cor } from "./cov.js";
|
|
12
13
|
import { sumOnce, varimax } from "./factanal.js";
|
|
14
|
+
import { maxOf } from "../internal/extremes.js";
|
|
13
15
|
const EPS = 2 ** -52;
|
|
14
16
|
const TWO_FACTOR_MESSAGE = "\nThree factors are required for identification -- general factor loadings set to be equal. \nProceed with caution. \nThink about redoing the analysis with alternative values of the 'option' setting.\n\n";
|
|
15
17
|
const matMul = (A, B) => A.map((row) => B[0].map((_, j) => {
|
|
@@ -81,13 +83,62 @@ function minres(S0, q, warnings, messages) {
|
|
|
81
83
|
return h + v - S[i][i];
|
|
82
84
|
});
|
|
83
85
|
};
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
86
|
+
// The objective's own derivative, from the first-order perturbation of the eigen pairs of S* (diagonal 1 - psi):
|
|
87
|
+
// de_k = -v_ik^2, dv_k = -sum_{l != k} v_l v_il v_ik / (e_k - e_l); W the off-diagonal residual, B = V'WV
|
|
88
|
+
const trueGradient = (psi) => {
|
|
89
|
+
const E = eigen(S.map((r, i) => r.map((v, j) => (i === j ? 1 - psi[i] : v))), { symmetric: true });
|
|
90
|
+
const e = E.values;
|
|
91
|
+
const V = E.vectors;
|
|
92
|
+
const live = e.map((v) => v >= EPS);
|
|
93
|
+
const et = e.map((v) => (v < EPS ? 100 * EPS : v));
|
|
94
|
+
const W = S.map((r, i) => r.map((v, j) => {
|
|
95
|
+
if (i === j)
|
|
96
|
+
return 0;
|
|
97
|
+
let m = 0;
|
|
98
|
+
for (let k = 0; k < q; k++)
|
|
99
|
+
m += et[k] * V[i][k] * V[j][k];
|
|
100
|
+
return v - m;
|
|
101
|
+
}));
|
|
102
|
+
const WV = matMul(W, V);
|
|
103
|
+
const B = (k, l) => {
|
|
104
|
+
let b = 0;
|
|
105
|
+
for (let i = 0; i < p; i++)
|
|
106
|
+
b += V[i][k] * WV[i][l];
|
|
107
|
+
return b;
|
|
108
|
+
};
|
|
109
|
+
const g = new Array(p).fill(0);
|
|
110
|
+
for (let k = 0; k < q; k++) {
|
|
111
|
+
const add = (l, r) => {
|
|
112
|
+
if (r === 0)
|
|
113
|
+
return;
|
|
114
|
+
const b = r * B(k, l);
|
|
115
|
+
for (let i = 0; i < p; i++)
|
|
116
|
+
g[i] += b * V[i][k] * V[i][l];
|
|
117
|
+
};
|
|
118
|
+
if (live[k])
|
|
119
|
+
add(k, 1);
|
|
120
|
+
for (let l = k + 1; l < q; l++)
|
|
121
|
+
add(l, 2 * (live[k] && live[l] ? 1 : (et[k] - et[l]) / (e[k] - e[l])));
|
|
122
|
+
for (let l = q; l < p; l++)
|
|
123
|
+
add(l, (2 * et[k]) / (e[k] - e[l]));
|
|
124
|
+
}
|
|
125
|
+
return g;
|
|
126
|
+
};
|
|
127
|
+
const lower = 0.005;
|
|
128
|
+
const bounds = { method: "L-BFGS-B", lower, upper: Math.max(maxOf(s), 1) };
|
|
129
|
+
const parscale = new Array(p).fill(0.01);
|
|
130
|
+
let fit = optim(s.map((v) => 1 - v), objective, { gr: gradient, ...bounds, control: { fnscale: 1, parscale } });
|
|
131
|
+
// psych's gradient is that of the residual sum of squares with the diagonal (zero where the off-diagonal objective
|
|
132
|
+
// is stationary), so its minimum is the objective's in the interior; with a uniqueness at the lower bound the two
|
|
133
|
+
// part, and the fit stops short of the minimum (#83). Go on from there with the objective's own gradient
|
|
134
|
+
if (fit.par.some((v) => v === lower)) {
|
|
135
|
+
fit = optim(fit.par, objective, { gr: trueGradient, ...bounds, control: { fnscale: 1, parscale, factr: 1e3 } });
|
|
136
|
+
}
|
|
137
|
+
// psych's fa goes on from the last point without a word when optim does not converge; the loadings, omegas and G6
|
|
138
|
+
// then come from uniquenesses that are not a minimum, so say so (the values are kept, as psych's)
|
|
139
|
+
if (fit.convergence !== 0) {
|
|
140
|
+
addMessage(warnings, `minres did not converge (optim convergence code ${fit.convergence}): examine the results carefully`);
|
|
141
|
+
}
|
|
91
142
|
const psi = fit.par;
|
|
92
143
|
let L = principalLoadings(S, psi.map((v, i) => S[i][i] - v), q, (e) => Math.max(e, 0));
|
|
93
144
|
L = signColumns(L, q);
|
|
@@ -163,7 +214,7 @@ function oblimin(A) {
|
|
|
163
214
|
else {
|
|
164
215
|
alpha = 2 * alpha;
|
|
165
216
|
}
|
|
166
|
-
const target =
|
|
217
|
+
const target = maxOf(values.slice(-10));
|
|
167
218
|
let trial = cur;
|
|
168
219
|
let Tt = T;
|
|
169
220
|
for (let i = 0; i <= 10; i++) {
|
|
@@ -187,7 +238,7 @@ function oblimin(A) {
|
|
|
187
238
|
* `option = "equal"`, `flip = TRUE`).
|
|
188
239
|
*
|
|
189
240
|
* @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
|
|
190
|
-
* or `null` with `options.covmat`.
|
|
241
|
+
* or `null` with `options.covmat`. At least 2 variables.
|
|
191
242
|
* @param options See {@link OmegaOptions}.
|
|
192
243
|
*
|
|
193
244
|
* @example
|
|
@@ -214,6 +265,7 @@ export function omega(x, options = {}) {
|
|
|
214
265
|
throw new RangeError("'nfactors' must be a positive integer");
|
|
215
266
|
let R;
|
|
216
267
|
if (options.covmat !== undefined) {
|
|
268
|
+
checkCovmat(options.covmat);
|
|
217
269
|
R = toCorrelation(options.covmat);
|
|
218
270
|
}
|
|
219
271
|
else {
|
|
@@ -222,6 +274,13 @@ export function omega(x, options = {}) {
|
|
|
222
274
|
R = cor(x, undefined, { use: "pairwise.complete.obs" });
|
|
223
275
|
}
|
|
224
276
|
const p = R.length;
|
|
277
|
+
// reliability of one item is not defined: psych stops ("'x' must be an array of at least two dimensions"); here
|
|
278
|
+
// omegaLim was Infinity and alpha NaN (#261)
|
|
279
|
+
if (p < 2)
|
|
280
|
+
throw new RangeError(`omega needs at least 2 variables (got ${p})`);
|
|
281
|
+
// psych stops on a subscript out of bounds there; the cause is said instead
|
|
282
|
+
if (q > p)
|
|
283
|
+
throw new RangeError(`'nfactors' (${q}) must not exceed the number of variables (${p})`);
|
|
225
284
|
const warnings = [];
|
|
226
285
|
const messages = [];
|
|
227
286
|
const orthog = minres(R, q, warnings, messages);
|
|
@@ -10,7 +10,7 @@ export interface PivotLongerOptions {
|
|
|
10
10
|
cols: readonly string[] | ((name: string) => boolean);
|
|
11
11
|
/**
|
|
12
12
|
* The columns to make from the names, one per part of the names. `".value"` marks the part that names the value
|
|
13
|
-
* columns. Default `"name"`.
|
|
13
|
+
* columns. With `[]`, no columns are made from the names (namesSep and namesPattern are not used). Default `"name"`.
|
|
14
14
|
*/
|
|
15
15
|
namesTo?: string | readonly string[];
|
|
16
16
|
/** A regular expression whose match at the start of the names is removed. */
|
|
@@ -19,7 +19,11 @@ export interface PivotLongerOptions {
|
|
|
19
19
|
namesSep?: string;
|
|
20
20
|
/** A regular expression whose capture groups are the parts of the names. */
|
|
21
21
|
namesPattern?: string;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Functions applied to the parts, by `namesTo` column (the part as a string; missing parts stay missing). Own
|
|
24
|
+
* properties only: a `namesTo` column named toString has no transform unless one is given. The transform of
|
|
25
|
+
* `".value"` gives the names of the value columns, and must return strings.
|
|
26
|
+
*/
|
|
23
27
|
namesTransform?: Readonly<Record<string, (part: string) => DataValue>>;
|
|
24
28
|
/** The name of the value column (without `".value"` in `namesTo`). Default `"value"`. */
|
|
25
29
|
valuesTo?: string;
|
|
@@ -27,7 +31,7 @@ export interface PivotLongerOptions {
|
|
|
27
31
|
valuesDropNa?: boolean;
|
|
28
32
|
/**
|
|
29
33
|
* `"fastest"` (default): the pivoted columns vary within each input row; `"slowest"`: all rows for each column in
|
|
30
|
-
* turn.
|
|
34
|
+
* turn. Any other value is an error, as in tidyr.
|
|
31
35
|
*/
|
|
32
36
|
colsVary?: "fastest" | "slowest";
|
|
33
37
|
/** Called with each of tidyr's warnings, once per distinct warning, in order. Default: the warnings are dropped. */
|
|
@@ -45,13 +49,13 @@ export type PivotSummary = (values: DataValue[]) => DataValue;
|
|
|
45
49
|
* @category Data frames
|
|
46
50
|
*/
|
|
47
51
|
export interface PivotWiderOptions {
|
|
48
|
-
/** The column (or columns) whose values name the new columns. Default `"name"`. */
|
|
52
|
+
/** The column (or columns) whose values name the new columns (at least one). Default `"name"`. */
|
|
49
53
|
namesFrom?: string | readonly string[];
|
|
50
|
-
/** The column (or columns) whose values fill the new columns. Default `"value"`. */
|
|
54
|
+
/** The column (or columns) whose values fill the new columns (at least one). Default `"value"`. */
|
|
51
55
|
valuesFrom?: string | readonly string[];
|
|
52
56
|
/**
|
|
53
57
|
* The columns that identify a row of the result. Default: every column not in `namesFrom` or `valuesFrom`, in the
|
|
54
|
-
* data's order; when given, the other columns are dropped.
|
|
58
|
+
* data's order; when given, the other columns are dropped (a column of `namesFrom` or `valuesFrom` is an error).
|
|
55
59
|
*/
|
|
56
60
|
idCols?: string | readonly string[];
|
|
57
61
|
/** Put before each new name. Default `""`. */
|
|
@@ -62,12 +66,20 @@ export interface PivotWiderOptions {
|
|
|
62
66
|
namesSort?: boolean;
|
|
63
67
|
/**
|
|
64
68
|
* With several `valuesFrom`: `"fastest"` (default) all names for each value column; `"slowest"` each value column
|
|
65
|
-
* for each name.
|
|
69
|
+
* for each name. Any other value is an error, as in tidyr.
|
|
66
70
|
*/
|
|
67
71
|
namesVary?: "fastest" | "slowest";
|
|
68
|
-
/**
|
|
72
|
+
/**
|
|
73
|
+
* The value of a cell that no row fills, or such values by value column. Default: missing. As in tidyr, it is cast
|
|
74
|
+
* to the type of the value column: a boolean becomes 0 or 1 in a numeric column, 0 and 1 become false and true in a
|
|
75
|
+
* boolean column (NaN missing); any other mix (a string with a number or a boolean) is an error.
|
|
76
|
+
*/
|
|
69
77
|
valuesFill?: DataValue | Readonly<Record<string, DataValue>>;
|
|
70
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* Summarises the values of each filled cell, or such functions by value column. As in tidyr, the results for one
|
|
80
|
+
* value column take one common type: booleans become 0 and 1 if any result is a number; strings mixed with numbers
|
|
81
|
+
* or booleans are an error.
|
|
82
|
+
*/
|
|
71
83
|
valuesFn?: PivotSummary | Readonly<Record<string, PivotSummary>>;
|
|
72
84
|
}
|
|
73
85
|
/**
|
|
@@ -9,6 +9,19 @@
|
|
|
9
9
|
import { formatR } from "../htest/core/simulate.js";
|
|
10
10
|
import { addColumn, compareValues, isMissing, pick, rowCount } from "./dataFrames.js";
|
|
11
11
|
const nameList = (v) => (typeof v === "string" ? [v] : [...v]);
|
|
12
|
+
/**
|
|
13
|
+
* colsVary or namesVary, checked as tidyr's arg_match: exactly "fastest" or "slowest" (default "fastest"); anything
|
|
14
|
+
* else was taken as "fastest" (#256)
|
|
15
|
+
*/
|
|
16
|
+
function varyArg(arg, v) {
|
|
17
|
+
if (v === undefined || v === null)
|
|
18
|
+
return "fastest";
|
|
19
|
+
if (v === "fastest" || v === "slowest")
|
|
20
|
+
return v;
|
|
21
|
+
if (typeof v !== "string")
|
|
22
|
+
throw new Error(`\`${arg}\` must be a string or character vector.`);
|
|
23
|
+
throw new Error(`\`${arg}\` must be one of "fastest" or "slowest", not "${v}".`);
|
|
24
|
+
}
|
|
12
25
|
function requireColumns(data, names) {
|
|
13
26
|
for (const n of names)
|
|
14
27
|
if (!Object.hasOwn(data, n))
|
|
@@ -59,21 +72,41 @@ function captures(names, pattern, count) {
|
|
|
59
72
|
return Array.from({ length: count }, (_, j) => (m === null ? null : (m[j + 1] ?? null)));
|
|
60
73
|
});
|
|
61
74
|
}
|
|
75
|
+
/** The number of UTF-16 code units of the character at i: 2 for a surrogate pair, else 1 */
|
|
76
|
+
function codePointLength(s, i) {
|
|
77
|
+
const c = s.charCodeAt(i);
|
|
78
|
+
if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
|
|
79
|
+
const d = s.charCodeAt(i + 1);
|
|
80
|
+
if (d >= 0xdc00 && d <= 0xdfff)
|
|
81
|
+
return 2;
|
|
82
|
+
}
|
|
83
|
+
return 1;
|
|
84
|
+
}
|
|
62
85
|
/** The names split at the separator into `count` parts, and tidyr's warnings for names with more or fewer pieces */
|
|
63
86
|
function separated(names, sep, count, warnings) {
|
|
64
87
|
const re = new RegExp(sep, "g");
|
|
65
88
|
const extra = [];
|
|
66
89
|
const short = [];
|
|
67
90
|
const parts = names.map((name, i) => {
|
|
91
|
+
// The pieces between the matches, as tidyr (R's gregexpr(perl = TRUE) and regmatches(invert = TRUE)): after a
|
|
92
|
+
// zero-width match the search goes on one character later, and it stops once it reaches the end of the name. A
|
|
93
|
+
// character is a code point: a surrogate pair is passed whole, as stringr's str_split (#500; R's gregexpr went on
|
|
94
|
+
// inside the character's UTF-8 bytes and gave empty pieces)
|
|
68
95
|
const pieces = [];
|
|
69
96
|
let start = 0;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
97
|
+
let prev = 0;
|
|
98
|
+
for (;;) {
|
|
99
|
+
re.lastIndex = start;
|
|
100
|
+
const m = re.exec(name);
|
|
101
|
+
if (m === null)
|
|
102
|
+
break;
|
|
103
|
+
pieces.push(name.slice(prev, m.index));
|
|
104
|
+
prev = m.index + m[0].length;
|
|
105
|
+
start = m[0].length === 0 ? m.index + codePointLength(name, m.index) : prev;
|
|
106
|
+
if (start >= name.length)
|
|
107
|
+
break;
|
|
75
108
|
}
|
|
76
|
-
pieces.push(name.slice(
|
|
109
|
+
pieces.push(name.slice(prev));
|
|
77
110
|
if (pieces.length > count)
|
|
78
111
|
extra.push(i + 1);
|
|
79
112
|
if (pieces.length < count)
|
|
@@ -87,16 +120,23 @@ function separated(names, sep, count, warnings) {
|
|
|
87
120
|
warnings.push(`Expected ${count} pieces. Missing pieces filled with \`NA\` in ${rows(short)}.`);
|
|
88
121
|
return parts;
|
|
89
122
|
}
|
|
123
|
+
/** The transform of a `namesTo` column (own properties only: toString has no transform unless one is given, #436) */
|
|
124
|
+
function ownTransform(transforms, to) {
|
|
125
|
+
return transforms !== undefined && Object.hasOwn(transforms, to) ? transforms[to] : undefined;
|
|
126
|
+
}
|
|
90
127
|
/** The parts of each name, one per element of `namesTo` */
|
|
91
128
|
function nameParts(names, namesTo, options, warnings) {
|
|
92
129
|
const { namesSep, namesPattern } = options;
|
|
130
|
+
// no names: no parts, and namesSep and namesPattern are not used (as tidyr's build_longer_spec)
|
|
131
|
+
if (namesTo.length === 0)
|
|
132
|
+
return names.map(() => []);
|
|
93
133
|
if (namesTo.length === 1) {
|
|
94
134
|
if (namesSep !== undefined)
|
|
95
135
|
throw new Error("`names_sep` can't be used with a length 1 `names_to`.");
|
|
96
136
|
if (namesPattern === undefined)
|
|
97
137
|
return names.map((n) => [n]);
|
|
98
|
-
|
|
99
|
-
return names
|
|
138
|
+
// exactly one capture group, as tidyr (no group gave null parts, a second group was ignored, #255)
|
|
139
|
+
return captures(names, namesPattern, 1);
|
|
100
140
|
}
|
|
101
141
|
if ((namesSep === undefined) === (namesPattern === undefined)) {
|
|
102
142
|
throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");
|
|
@@ -121,6 +161,7 @@ function nameParts(names, namesTo, options, warnings) {
|
|
|
121
161
|
* @category Data frames
|
|
122
162
|
*/
|
|
123
163
|
export function pivotLonger(data, options) {
|
|
164
|
+
const colsVary = varyArg("cols_vary", options.colsVary);
|
|
124
165
|
const n = rowCount(data);
|
|
125
166
|
const allNames = Object.keys(data);
|
|
126
167
|
const cols = typeof options.cols === "function" ? allNames.filter(options.cols) : [...new Set(options.cols)];
|
|
@@ -145,6 +186,7 @@ export function pivotLonger(data, options) {
|
|
|
145
186
|
else {
|
|
146
187
|
const keyIndex = new Map();
|
|
147
188
|
const valueIndex = new Map();
|
|
189
|
+
const valueTransform = ownTransform(options.namesTransform, ".value");
|
|
148
190
|
parts.forEach((p, c) => {
|
|
149
191
|
const key = p.filter((_, j) => j !== valuePosition);
|
|
150
192
|
const id = JSON.stringify(key);
|
|
@@ -156,7 +198,13 @@ export function pivotLonger(data, options) {
|
|
|
156
198
|
for (const v of values)
|
|
157
199
|
v.sources.push(null);
|
|
158
200
|
}
|
|
159
|
-
|
|
201
|
+
// the transform of ".value" names the value columns, as tidyr (missing parts stay missing)
|
|
202
|
+
const part = p[valuePosition] ?? null;
|
|
203
|
+
const transformed = part === null || valueTransform === undefined ? part : valueTransform(part);
|
|
204
|
+
if (transformed !== null && typeof transformed !== "string") {
|
|
205
|
+
throw new Error(`the transform of \`.value\` must give strings, not ${typeof transformed}`);
|
|
206
|
+
}
|
|
207
|
+
const name = transformed ?? "NA";
|
|
160
208
|
let value = valueIndex.get(name);
|
|
161
209
|
if (value === undefined) {
|
|
162
210
|
value = { name, sources: keys.map(() => null) };
|
|
@@ -171,7 +219,7 @@ export function pivotLonger(data, options) {
|
|
|
171
219
|
const types = values.map((v) => commonType(data, v.sources.filter((s) => s !== null)));
|
|
172
220
|
// Rows of the result: [input row, key]
|
|
173
221
|
let rows = [];
|
|
174
|
-
if (
|
|
222
|
+
if (colsVary === "slowest") {
|
|
175
223
|
for (let k = 0; k < keys.length; k++)
|
|
176
224
|
for (let i = 0; i < n; i++)
|
|
177
225
|
rows.push([i, k]);
|
|
@@ -196,7 +244,7 @@ export function pivotLonger(data, options) {
|
|
|
196
244
|
namesTo.forEach((to, j) => {
|
|
197
245
|
if (j === valuePosition)
|
|
198
246
|
return;
|
|
199
|
-
const transform = options.namesTransform
|
|
247
|
+
const transform = ownTransform(options.namesTransform, to);
|
|
200
248
|
const part = (k) => {
|
|
201
249
|
const p = keys[k][j < valuePosition || valuePosition < 0 ? j : j - 1];
|
|
202
250
|
return p === null || transform === undefined ? p : transform(p);
|
|
@@ -222,6 +270,26 @@ export function pivotLonger(data, options) {
|
|
|
222
270
|
return out;
|
|
223
271
|
}
|
|
224
272
|
// ---- pivotWider ----
|
|
273
|
+
const typeOfValue = (x) => typeof x === "number" ? "double" : typeof x === "string" ? "character" : "logical";
|
|
274
|
+
/** valuesFill cast to the type of the value column, as vctrs' vec_cast (a missing fill goes with any type) */
|
|
275
|
+
function castFill(fill, type) {
|
|
276
|
+
if (fill === null || type === null)
|
|
277
|
+
return fill;
|
|
278
|
+
const from = typeOfValue(fill);
|
|
279
|
+
if (from === type)
|
|
280
|
+
return fill;
|
|
281
|
+
if (type === "double" && from === "logical")
|
|
282
|
+
return Number(fill);
|
|
283
|
+
if (type === "logical" && from === "double") {
|
|
284
|
+
const x = fill;
|
|
285
|
+
if (Number.isNaN(x))
|
|
286
|
+
return null;
|
|
287
|
+
if (x === 0 || x === 1)
|
|
288
|
+
return x === 1;
|
|
289
|
+
throw new TypeError("Can't convert from `fill` <double> to <logical> due to loss of precision.");
|
|
290
|
+
}
|
|
291
|
+
throw new TypeError(`Can't convert \`fill\` <${from}> to <${type}>.`);
|
|
292
|
+
}
|
|
225
293
|
/** A value as an exact key (missing values are all one key) */
|
|
226
294
|
const keyOf = (v) => isMissing(v) ? "NA" : typeof v === "number" ? `n${v}` : typeof v === "string" ? `s${v}` : `b${String(v)}`;
|
|
227
295
|
/**
|
|
@@ -253,11 +321,14 @@ function labelText(v) {
|
|
|
253
321
|
return v ? "TRUE" : "FALSE";
|
|
254
322
|
return v;
|
|
255
323
|
}
|
|
256
|
-
/** An option given once for all value columns or by value column
|
|
324
|
+
/** An option given once for all value columns or by value column (own properties only: a column named toString or
|
|
325
|
+
* __proto__ has no setting unless one is given) */
|
|
257
326
|
function perColumn(option, isSingle, name) {
|
|
258
327
|
if (option === undefined)
|
|
259
328
|
return undefined;
|
|
260
|
-
|
|
329
|
+
if (isSingle(option))
|
|
330
|
+
return option;
|
|
331
|
+
return Object.hasOwn(option, name) ? option[name] : undefined;
|
|
261
332
|
}
|
|
262
333
|
/**
|
|
263
334
|
* Reshapes a data frame from long to wide: the values of `namesFrom` become columns, filled from `valuesFrom`.
|
|
@@ -276,13 +347,29 @@ function perColumn(option, isSingle, name) {
|
|
|
276
347
|
* @category Data frames
|
|
277
348
|
*/
|
|
278
349
|
export function pivotWider(data, options = {}) {
|
|
350
|
+
const namesVary = varyArg("names_vary", options.namesVary);
|
|
279
351
|
const n = rowCount(data);
|
|
280
|
-
|
|
281
|
-
|
|
352
|
+
// As tidyr: names_from, then values_from, each existing and not empty; then id_cols. A name given twice is
|
|
353
|
+
// selected once, at its first place (as tidyselect)
|
|
354
|
+
const selection = (v, arg) => {
|
|
355
|
+
const names = [...new Set(nameList(v))];
|
|
356
|
+
requireColumns(data, names);
|
|
357
|
+
if (names.length === 0)
|
|
358
|
+
throw new Error(`\`${arg}\` must select at least one column.`);
|
|
359
|
+
return names;
|
|
360
|
+
};
|
|
361
|
+
const namesFrom = selection(options.namesFrom ?? "name", "names_from");
|
|
362
|
+
const valuesFrom = selection(options.valuesFrom ?? "value", "values_from");
|
|
282
363
|
const idCols = options.idCols === undefined
|
|
283
364
|
? Object.keys(data).filter((c) => !namesFrom.includes(c) && !valuesFrom.includes(c))
|
|
284
|
-
: nameList(options.idCols);
|
|
285
|
-
requireColumns(data,
|
|
365
|
+
: [...new Set(nameList(options.idCols))];
|
|
366
|
+
requireColumns(data, idCols);
|
|
367
|
+
for (const c of idCols) {
|
|
368
|
+
const by = namesFrom.includes(c) ? "names_from" : valuesFrom.includes(c) ? "values_from" : null;
|
|
369
|
+
if (by !== null) {
|
|
370
|
+
throw new Error(`\`id_cols\` can't select a column already selected by \`${by}\`. Column \`${c}\` has already been selected.`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
286
373
|
const prefix = options.namesPrefix ?? "";
|
|
287
374
|
const sep = options.namesSep ?? "_";
|
|
288
375
|
const ids = combinations(idCols.map((c) => data[c]), n);
|
|
@@ -307,33 +394,72 @@ export function pivotWider(data, options = {}) {
|
|
|
307
394
|
cellRows[ids.codes[i] * nNames + labels.codes[i]].push(i);
|
|
308
395
|
const isSummary = (o) => typeof o === "function";
|
|
309
396
|
const isFill = (o) => typeof o !== "object" || o === null;
|
|
310
|
-
const columnOf = (value, m) => {
|
|
311
|
-
const source = data[value];
|
|
312
|
-
const summary = perColumn(options.valuesFn, isSummary, value);
|
|
313
|
-
const fill = perColumn(options.valuesFill, isFill, value) ?? null;
|
|
314
|
-
const cells = ids.firsts.map((_, r) => {
|
|
315
|
-
const rows = cellRows[r * nNames + m];
|
|
316
|
-
if (rows.length === 0)
|
|
317
|
-
return fill;
|
|
318
|
-
if (summary !== undefined)
|
|
319
|
-
return summary(rows.map((i) => source[i]));
|
|
320
|
-
return source[rows[0]];
|
|
321
|
-
});
|
|
322
|
-
if (source instanceof Float64Array && cells.every((x) => x === null || typeof x === "number")) {
|
|
323
|
-
return Float64Array.from(cells, (x) => (x === null ? NaN : x));
|
|
324
|
-
}
|
|
325
|
-
return cells;
|
|
326
|
-
};
|
|
327
397
|
for (const value of valuesFrom) {
|
|
328
398
|
if (perColumn(options.valuesFn, isSummary, value) === undefined && cellRows.some((rows) => rows.length > 1)) {
|
|
329
399
|
throw new Error(`values from '${value}' are not uniquely identified; use valuesFn to summarise them`);
|
|
330
400
|
}
|
|
331
401
|
}
|
|
402
|
+
// As tidyr: the filled cells of a value column (after valuesFn, called in order of first appearance of the cell)
|
|
403
|
+
// have one common type over all its new columns (numbers absorb booleans, strings combine with neither), and
|
|
404
|
+
// valuesFill is cast to that type (#437, #445)
|
|
405
|
+
const typed = new Map();
|
|
406
|
+
for (const value of valuesFrom) {
|
|
407
|
+
const source = data[value];
|
|
408
|
+
const summary = perColumn(options.valuesFn, isSummary, value);
|
|
409
|
+
const cells = new Array(cellRows.length).fill(null);
|
|
410
|
+
let type = null;
|
|
411
|
+
if (summary === undefined) {
|
|
412
|
+
type = columnType(value, source);
|
|
413
|
+
cellRows.forEach((rows, c) => {
|
|
414
|
+
if (rows.length > 0)
|
|
415
|
+
cells[c] = source[rows[0]];
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
else {
|
|
419
|
+
const done = new Uint8Array(cellRows.length);
|
|
420
|
+
let first = 0;
|
|
421
|
+
let k = 0;
|
|
422
|
+
for (let i = 0; i < n; i++) {
|
|
423
|
+
const c = ids.codes[i] * nNames + labels.codes[i];
|
|
424
|
+
if (done[c] === 1)
|
|
425
|
+
continue;
|
|
426
|
+
done[c] = 1;
|
|
427
|
+
k++;
|
|
428
|
+
const x = summary(cellRows[c].map((j) => source[j]));
|
|
429
|
+
cells[c] = x;
|
|
430
|
+
if (x === null || x === undefined)
|
|
431
|
+
continue;
|
|
432
|
+
const t = typeOfValue(x);
|
|
433
|
+
if (type === null || (type === "logical" && t === "double")) {
|
|
434
|
+
type = t;
|
|
435
|
+
first = k;
|
|
436
|
+
}
|
|
437
|
+
else if (t !== type && (type === "character" || t === "character")) {
|
|
438
|
+
throw new TypeError(`Can't combine \`x[[${first}]]\` <${type}> and \`x[[${k}]]\` <${t}>.`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
const fill = castFill(perColumn(options.valuesFill, isFill, value) ?? null, type);
|
|
443
|
+
typed.set(value, { cells, type: type ?? (fill === null ? null : typeOfValue(fill)), fill });
|
|
444
|
+
}
|
|
445
|
+
const columnOf = (value, m) => {
|
|
446
|
+
const source = data[value];
|
|
447
|
+
const { cells, type, fill } = typed.get(value);
|
|
448
|
+
const col = ids.firsts.map((_, r) => {
|
|
449
|
+
const c = r * nNames + m;
|
|
450
|
+
const x = cellRows[c].length === 0 ? fill : cells[c];
|
|
451
|
+
return type === "double" && typeof x === "boolean" ? Number(x) : x;
|
|
452
|
+
});
|
|
453
|
+
if (source instanceof Float64Array && (type === "double" || type === null)) {
|
|
454
|
+
return Float64Array.from(col, (x) => (x === null ? NaN : x));
|
|
455
|
+
}
|
|
456
|
+
return col;
|
|
457
|
+
};
|
|
332
458
|
const out = {};
|
|
333
459
|
for (const c of idCols)
|
|
334
460
|
addColumn(out, c, pick(data[c], ids.firsts));
|
|
335
461
|
const columnName = (value, m) => valuesFrom.length === 1 ? nameText[m] : `${value}${sep}${nameText[m]}`;
|
|
336
|
-
if (
|
|
462
|
+
if (namesVary === "slowest") {
|
|
337
463
|
for (const m of nameOrder)
|
|
338
464
|
for (const v of valuesFrom)
|
|
339
465
|
addColumn(out, columnName(v, m), columnOf(v, m));
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// position meant to be an integer is not lost to rounding, and treat a fractional part below 4 eps as 0. fivenum is
|
|
9
9
|
// Tukey's five-number summary; mad scales by 1.4826 by default.
|
|
10
10
|
import { median, values } from "./basic.js";
|
|
11
|
+
import { midpoint } from "../internal/extremes.js";
|
|
11
12
|
/** Relative fuzz for the positions of types 1 to 6, 8 and 9 */
|
|
12
13
|
const FUZZ = 4 * Number.EPSILON;
|
|
13
14
|
/** (a, b) of the continuous types 4 to 6, 8 and 9 (Hyndman and Fan's p(k) = (k - a) / (n + 1 - a - b)) */
|
|
@@ -115,7 +116,7 @@ export function fivenum(x) {
|
|
|
115
116
|
return [NaN, NaN, NaN, NaN, NaN];
|
|
116
117
|
const n4 = Math.floor((n + 3) / 2) / 2;
|
|
117
118
|
const d = [1, n4, (n + 1) / 2, n + 1 - n4, n];
|
|
118
|
-
return d.map((v) =>
|
|
119
|
+
return d.map((v) => midpoint(s[Math.floor(v) - 1], s[Math.ceil(v) - 1]));
|
|
119
120
|
}
|
|
120
121
|
/**
|
|
121
122
|
* Median absolute deviation, scaled. Equivalent to R's `mad()`.
|
package/dist/descriptive/rank.js
CHANGED
|
@@ -12,7 +12,8 @@ function rankValues(x, method) {
|
|
|
12
12
|
const u = method === "random" ? runif(n) : [];
|
|
13
13
|
const idx = Array.from({ length: n }, (_, i) => i);
|
|
14
14
|
idx.sort((a, b) => {
|
|
15
|
-
|
|
15
|
+
// compared, not subtracted: Infinity - Infinity is NaN, which would hide the tie
|
|
16
|
+
const d = x[a] < x[b] ? -1 : x[a] > x[b] ? 1 : 0;
|
|
16
17
|
if (d !== 0)
|
|
17
18
|
return d;
|
|
18
19
|
if (method === "first")
|
|
@@ -54,6 +55,8 @@ export function rank(x, options = {}) {
|
|
|
54
55
|
throw new RangeError(`invalid tiesMethod "${method}"`);
|
|
55
56
|
}
|
|
56
57
|
const naLast = options.naLast ?? "last";
|
|
58
|
+
if (naLast !== "last" && naLast !== "first" && naLast !== "keep")
|
|
59
|
+
throw new RangeError(`invalid 'naLast': ${String(naLast)}`);
|
|
57
60
|
const xs = Array.from(x);
|
|
58
61
|
const present = xs.filter((v) => !Number.isNaN(v));
|
|
59
62
|
const r = rankValues(present, method);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Sample } from "../htest/types.js";
|
|
2
2
|
/**
|
|
3
|
-
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others
|
|
3
|
+
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others, NaN, infinite values and values
|
|
4
|
+
* beyond the integer range of R are not counted).
|
|
4
5
|
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin) and is truncated towards 0, as R does.
|
|
5
6
|
*
|
|
6
7
|
* @example
|
|
@@ -64,7 +65,7 @@ export interface CutOptions {
|
|
|
64
65
|
/**
|
|
65
66
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
66
67
|
*
|
|
67
|
-
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left
|
|
68
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left are an error), or a
|
|
68
69
|
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
69
70
|
* each end, as R does. That range must be finite.
|
|
70
71
|
*
|
|
@@ -6,8 +6,10 @@
|
|
|
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
|
+
import { maxOf, minOf } from "../internal/extremes.js";
|
|
9
10
|
/**
|
|
10
|
-
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others
|
|
11
|
+
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others, NaN, infinite values and values
|
|
12
|
+
* beyond the integer range of R are not counted).
|
|
11
13
|
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin) and is truncated towards 0, as R does.
|
|
12
14
|
*
|
|
13
15
|
* @example
|
|
@@ -19,7 +21,13 @@ import { seqLength } from "../internal/seq.js";
|
|
|
19
21
|
* @category Descriptive statistics
|
|
20
22
|
*/
|
|
21
23
|
export function tabulate(bin, nbins) {
|
|
22
|
-
|
|
24
|
+
// as R's as.integer: truncated, and NA (here NaN) when infinite or outside the integer range, so such a value is
|
|
25
|
+
// not counted and does not set the default nbins (Infinity was an array of infinite length, 3e9 ran out of memory,
|
|
26
|
+
// #225)
|
|
27
|
+
const b = Array.from(bin, (v) => {
|
|
28
|
+
const t = Math.trunc(v);
|
|
29
|
+
return t >= -2147483647 && t <= 2147483647 ? t : NaN;
|
|
30
|
+
});
|
|
23
31
|
if (nbins !== undefined) {
|
|
24
32
|
if (Number.isNaN(nbins))
|
|
25
33
|
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
@@ -28,7 +36,7 @@ export function tabulate(bin, nbins) {
|
|
|
28
36
|
if (Math.trunc(nbins) >= 2 ** 31)
|
|
29
37
|
throw new RangeError("attempt to make a table with >= 2^31 elements");
|
|
30
38
|
}
|
|
31
|
-
const nb = nbins === undefined ? Math.max(1,
|
|
39
|
+
const nb = nbins === undefined ? Math.max(1, maxOf(b.filter((v) => !Number.isNaN(v)))) : Math.trunc(nbins);
|
|
32
40
|
const out = new Array(Math.max(0, nb)).fill(0);
|
|
33
41
|
for (const v of b)
|
|
34
42
|
if (v >= 1 && v <= nb)
|
|
@@ -49,6 +57,9 @@ export function tabulate(bin, nbins) {
|
|
|
49
57
|
*/
|
|
50
58
|
export function table(x, options = {}) {
|
|
51
59
|
const useNA = options.useNA ?? "no";
|
|
60
|
+
// (as R's match.arg; any other value was taken as "no", silently dropping the count of missing values; issue #18)
|
|
61
|
+
if (useNA !== "no" && useNA !== "ifany" && useNA !== "always")
|
|
62
|
+
throw new RangeError("'arg' should be one of “no”, “ifany”, “always”");
|
|
52
63
|
const xs = numberLevels(Array.from(x));
|
|
53
64
|
const map = new Map();
|
|
54
65
|
let nas = 0;
|
|
@@ -91,7 +102,7 @@ export function unique(x) {
|
|
|
91
102
|
/**
|
|
92
103
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
93
104
|
*
|
|
94
|
-
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left
|
|
105
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left are an error), or a
|
|
95
106
|
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
96
107
|
* each end, as R does. That range must be finite.
|
|
97
108
|
*
|
|
@@ -114,8 +125,8 @@ export function cut(x, breaks, options = {}) {
|
|
|
114
125
|
throw new RangeError("invalid number of intervals");
|
|
115
126
|
const nb = Math.trunc(k + 1);
|
|
116
127
|
const present = xs.filter((v) => !Number.isNaN(v));
|
|
117
|
-
const lo =
|
|
118
|
-
const hi =
|
|
128
|
+
const lo = minOf(present);
|
|
129
|
+
const hi = maxOf(present);
|
|
119
130
|
// R's errors for a range that is not finite: the same infinity everywhere fails before the checks of the ends
|
|
120
131
|
if (present.length > 0 && lo === hi && !Number.isFinite(lo))
|
|
121
132
|
throw new RangeError("missing value where TRUE/FALSE needed");
|
|
@@ -134,8 +145,12 @@ export function cut(x, breaks, options = {}) {
|
|
|
134
145
|
br[nb - 1] = hi + dx / 1000;
|
|
135
146
|
}
|
|
136
147
|
}
|
|
137
|
-
else
|
|
148
|
+
else {
|
|
138
149
|
br = breaks.filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
|
|
150
|
+
// no interval to code: the error of one break (R gives NA codes for none, or one left after dropping NaN; #227)
|
|
151
|
+
if (br.length < 2)
|
|
152
|
+
throw new RangeError("invalid number of intervals");
|
|
153
|
+
}
|
|
139
154
|
if (new Set(br).size < br.length)
|
|
140
155
|
throw new RangeError("'breaks' are not unique");
|
|
141
156
|
return binCode(xs, br, right, includeLowest);
|
|
@@ -150,7 +165,7 @@ function binCode(xs, br, right, includeLowest) {
|
|
|
150
165
|
let lo = 0;
|
|
151
166
|
let hi = nb;
|
|
152
167
|
while (lo < hi) {
|
|
153
|
-
const mid = (lo + hi) >> 1
|
|
168
|
+
const mid = Math.floor((lo + hi) / 2); // not >> 1, which wraps beyond 2^31 breaks (issue #340)
|
|
154
169
|
if (right ? br[mid] < v : br[mid] <= v)
|
|
155
170
|
lo = mid + 1;
|
|
156
171
|
else
|
|
@@ -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
|