@numero-uno-jpn/rstats 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/README.ja.md +33 -15
  3. package/README.md +32 -14
  4. package/dist/chunks/{chunk-4KCSBTR5.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-Z2HGLFZN.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-U7BRXOUS.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-GJEKNJP7.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-GRUQRNX7.js → chunk-BNTBZ5W3.js} +3 -3
  10. package/dist/chunks/{chunk-DR4GQ7PW.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-OG7UORIX.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-N5BDSMXS.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-GGJA3JRO.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-HRA7PCQT.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-YN5MLKDL.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-GYGQUYEP.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-X4J6UJHN.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-DTJG2IL2.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-4VRMAYPY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/chunk-P7ZHH2SF.js +2 -0
  23. package/dist/chunks/{chunk-HUWOSLKE.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-7KJ24LYK.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-QUTJEYDX.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-HZLSNJQM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-EJYCDE4Z.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7IJCUSA5.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-JNWWLNE3.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +14 -0
  33. package/dist/entries/tests.js +14 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/binomCI.d.ts +116 -0
  36. package/dist/htest/binomCI.js +252 -0
  37. package/dist/htest/blandAltman.d.ts +100 -0
  38. package/dist/htest/blandAltman.js +159 -0
  39. package/dist/htest/boschlooTest.d.ts +65 -0
  40. package/dist/htest/boschlooTest.js +394 -0
  41. package/dist/htest/chisqTest.d.ts +19 -0
  42. package/dist/htest/chisqTest.js +30 -2
  43. package/dist/htest/core/twoProportions.d.ts +48 -0
  44. package/dist/htest/core/twoProportions.js +476 -0
  45. package/dist/htest/diagnosticTests.d.ts +91 -0
  46. package/dist/htest/diagnosticTests.js +116 -0
  47. package/dist/htest/equivalence.d.ts +172 -0
  48. package/dist/htest/equivalence.js +189 -0
  49. package/dist/htest/fisherTest.d.ts +49 -0
  50. package/dist/htest/fisherTest.js +136 -13
  51. package/dist/htest/iccPsych.d.ts +106 -0
  52. package/dist/htest/iccPsych.js +332 -0
  53. package/dist/htest/ksTest.d.ts +1 -1
  54. package/dist/htest/mcreg.d.ts +209 -0
  55. package/dist/htest/mcreg.js +735 -0
  56. package/dist/htest/roc.d.ts +287 -0
  57. package/dist/htest/roc.js +635 -0
  58. package/dist/htest/rocTest.d.ts +139 -0
  59. package/dist/htest/rocTest.js +444 -0
  60. package/dist/htest/tTOST.d.ts +202 -0
  61. package/dist/htest/tTOST.js +558 -0
  62. package/dist/htest/tableTests.d.ts +216 -0
  63. package/dist/htest/tableTests.js +650 -0
  64. package/dist/htest/trendTests.d.ts +1 -1
  65. package/dist/htest/trendTests.js +1 -1
  66. package/dist/htest/twoByTwo.d.ts +203 -0
  67. package/dist/htest/twoByTwo.js +385 -0
  68. package/dist/internal/summary.js +5 -0
  69. package/dist/linalg/qr.d.ts +3 -0
  70. package/dist/linalg/qr.js +3 -0
  71. package/dist/linalg.js +2 -2
  72. package/dist/mixed.js +2 -2
  73. package/dist/models/coeftest.d.ts +139 -0
  74. package/dist/models/coeftest.js +237 -0
  75. package/dist/models/coxph.d.ts +60 -9
  76. package/dist/models/coxph.js +367 -38
  77. package/dist/models/glm.d.ts +11 -1
  78. package/dist/models/glm.js +19 -2
  79. package/dist/models/inputRows.d.ts +10 -0
  80. package/dist/models/inputRows.js +23 -0
  81. package/dist/models/lm.d.ts +8 -0
  82. package/dist/models/lm.js +14 -2
  83. package/dist/models/sandwich.d.ts +177 -0
  84. package/dist/models/sandwich.js +923 -0
  85. package/dist/numerics.js +2 -2
  86. package/dist/random/rng.d.ts +8 -1
  87. package/dist/random/rng.js +14 -1
  88. package/dist/rstats.js +16 -16
  89. package/dist/special/igam.js +140 -23
  90. package/dist/special/loader.js +8 -0
  91. package/dist/special.js +2 -2
  92. package/dist/tests.js +13 -13
  93. package/llms.txt +25 -0
  94. package/package.json +1 -1
  95. package/dist/chunks/chunk-NDTJ23A6.js +0 -2
  96. package/dist/chunks/chunk-UMLMY4XS.js +0 -2
  97. package/dist/chunks/chunk-Y4YWLSWU.js +0 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,148 @@ While the version is 0.x, a minor release (0.y.0) may contain breaking changes;
7
7
  they are listed under **Breaking** for each release. From 1.0.0 the project follows
8
8
  [Semantic Versioning](https://semver.org/).
9
9
 
10
+ ## 1.3.0 - 2026-11-09
11
+
12
+ Robust standard errors and diagnostic accuracy and measurement agreement (items 1 and 2 of the roadmap): sandwich's
13
+ heteroskedasticity-consistent and clustered covariances of lm and glm fits with lmtest's tests and intervals, the
14
+ robust variance of coxph, ROC curves with DeLong's and the bootstrap intervals and tests, the diagnostic 2 × 2
15
+ measures, Bland-Altman analysis, Deming and Passing-Bablok regression, the six Shrout-Fleiss intraclass correlations
16
+ and TOSTER's equivalence tests, checked against sandwich, lmtest, survival, pROC, epiR, BlandAltmanLeh, mcr, psych and
17
+ TOSTER (R 4.6.2); where these packages lose digits or overflow, the true values.
18
+
19
+ ### Added
20
+
21
+ - **Robust covariances** of `lm` (matrix and formula) and `glm` fits: `vcovHC(fit, { type, omega, sandwich })`,
22
+ sandwich's `vcovHC()`, with the types `const`, `HC0` (`HC`), `HC1`, `HC2`, `HC3` (default), `HC4`, `HC4m` and
23
+ `HC5` and omega as an array or a function `(res, hat, df) => omega`; `vcovCL(fit, { cluster, type, cadjust,
24
+ multi0, fix, sandwich })`, sandwich's `vcovCL()`, one-way and multi-way, with `HC0` and `HC1` (the default for an
25
+ lm; `HC0` for a glm) and `HC2`/`HC3` in the symmetric form of Bell and McCaffrey (for HC3 the leave-one-cluster-out
26
+ jackknife). Both return `{ vcov, names, warnings }`. Rows of prior weight 0 are left out, `const` is the
27
+ model-based covariance, cluster intersections are tuples of labels, and a hat value of 1 (HC2 to HC5), a singular
28
+ cluster block or a single cluster is an error (docs/differences-from-r.md).
29
+ - **Tests and intervals with a given covariance**: `coeftest(fit, { vcov, df })` and `coefci(fit, { parm, level,
30
+ vcov, df })`, lmtest's `coeftest()` and `coefci()`: t tests on the residual degrees of freedom of an lm, z tests
31
+ for a glm of every family; `vcov` is a matrix, the result of `vcovHC`/`vcovCL` or a function of the fit.
32
+ - `LmResult` has the model matrix `x`, the `weights` and the 0-based input `rows` used (as `LmFormulaResult` had),
33
+ and `GlmModel` the `rows` used.
34
+ - **Robust variance of `coxph`** (survival's `coxph(robust, cluster)`; Lin and Wei 1989): options `robust` (default
35
+ as R: on with a `cluster` or a case weight that is not an integer) and `cluster` (rows with a missing label are
36
+ dropped). The result has `usedRobust` always and, with the robust variance, `naiveVar`, `robustSe`, `rscore` and
37
+ `robscore`; `var` is then the robust variance and `z`, `p`, `lower`, `upper`, `wald` and `waldtest` use it, while
38
+ `se` stays the model-based standard error (R's `se(coef)`). Efron and Breslow ties, case weights and strata, R's
39
+ warning for a cluster with `robust: false`; a single cluster is an error (docs/differences-from-r.md). Non-integer
40
+ case weights no longer throw. Checked against survival 3.8-12 (R 4.6.2). The score residuals shift each risk set by
41
+ its own largest linear predictor (finite where the linear predictors span more than exp's range), and the robust
42
+ variance and `rscore` do not depend on the scale of the weights.
43
+ - **ROC curves** (pROC 1.19.1): `roc(response, predictor, { levels, direction, naRm })`, `roc(formula, data)` and
44
+ `roc({ controls, cases })`, pROC's `roc()`, with pROC's thresholds, stored order and "auto" direction (the median
45
+ rule), and the AUC from the counts; `auc(curve, { partialAuc, focus, correct })`, the partial AUC with McClish's
46
+ correction; `ciAuc(curve, { confLevel, method, bootN, bootStratified })`, `ci.auc()`, DeLong's interval and variance
47
+ or the bootstrap on R's random stream; `rocTest(roc1, roc2, options)` and `rocTest(response, predictor1,
48
+ predictor2, options)`, `roc.test()`, DeLong's paired and unpaired tests and the bootstrap test, pairing curves of the
49
+ same response as pROC; `coords(curve, x, { bestMethod, bestWeights })`, `coords(ret = "all")`, as column arrays.
50
+ The coordinates are computed from the integer counts and the "best" thresholds compared exactly, where pROC loses
51
+ digits and tied thresholds; one case or one control for DeLong's methods, infinite predictor values and limits
52
+ outside [0, 1] are errors (docs/differences-from-r.md).
53
+ - **Diagnostic 2 × 2 measures**: `diagnosticTests(table, { method, confLevel, prevalence })`, epiR's `epi.tests()`:
54
+ sensitivity, specificity, predictive values, likelihood ratios (log intervals), accuracy, the diagnostic odds ratio
55
+ (Woolf) and the true and apparent prevalence, with exact (Clopper-Pearson, computed directly), Wilson or Jeffreys
56
+ intervals, and the predictive values at a given prevalence.
57
+ - **Bland-Altman analysis**: `blandAltman(x, y, { two, mode, confLevel, ciMethod })`, BlandAltmanLeh's
58
+ `bland.altman.stats()`: the mean difference, the limits of agreement and their intervals, with the package's
59
+ `sqrt(3 s²/n)` interval of the limits (default) or the exact one from the noncentral t (`ciMethod: "exact"`, Carkeet
60
+ 2015). Fewer than 2 complete pairs is an error; data of any scale (docs/differences-from-r.md).
61
+ - **Method comparison regression**: `mcreg(x, y, { methodReg, methodCi, methodBootstrapCi, errorRatio, confLevel,
62
+ slopeMeasure, nsamples, nnested, rngSeed, iterMax, threshold, naRm })`, mcr's `mcreg()`: Deming, weighted Deming
63
+ (constant CV) and Passing-Bablok regression with analytical, jackknife and bootstrap intervals (quantile, Student,
64
+ BCa, bootstrap-t, nested bootstrap) drawn from R's random stream (`rngSeed` = mcr's `rng.seed`), and Passing and
65
+ Bablok's CUSUM statistic of linearity. The default interval is analytical (jackknife for weighted Deming) instead of
66
+ mcr's random bootstrap; Deming's slope without mcr's cancellation for small error ratios (docs/differences-from-r.md).
67
+ - **Intraclass correlations of Shrout and Fleiss**: `ICC(x, { alpha | confLevel, lmer })`, psych's `ICC()`, returning
68
+ the six forms (ICC1, ICC2, ICC3 and their averages) with their F tests and intervals and the mean squares, next to
69
+ the irr-based `icc`. Both paths are exact: the ANOVA mean squares (`lmer: false`) and, by default as psych, the REML
70
+ estimates of the variance components in closed form (lme4's optimiser leaves psych's values 1e-5 to 1e-4 off).
71
+ Complete data only; ICC2k has psych's interval (Spearman-Brown of ICC2's), not irr's.
72
+ - **Equivalence and minimal-effect t tests**: `tTOST(x, y?, options)`, TOSTER's `t_TOST()`, for one, two (Welch or
73
+ pooled) and paired samples, with bounds in raw or SMD units, the three t tests, the raw difference and the
74
+ standardised mean difference (Hedges' g or Cohen's d, d_av, d_z, d_rm, Glass's delta) with `nct` (exact roots),
75
+ `goulet`, `t` or `z` intervals; `tsumTOST(stats, options)`, TOSTER's `tsum_TOST()`, from summary statistics. `tost`
76
+ is unchanged. Unlike TOSTER, `mu` is subtracted everywhere (bound tests, raw interval and SMD of the difference
77
+ minus mu), the one-sample `t` and `z` limits are 1 − 2α limits, and TOSTER's notes are warnings
78
+ (docs/differences-from-r.md).
79
+
80
+ ### Fixed
81
+
82
+ - **`coxph` with case weights around 2^±512 or beyond** (all weights times 2^-560 or 2^600): the information
83
+ overflowed or underflowed (it was formed as a product that scales as the square of the weights), giving NaN
84
+ coefficients without a warning or "Ran out of iterations"; it is now formed as a quotient first where that product
85
+ leaves the doubles (ordinary fits keep their bits). An infinite case weight is now an error "'weights' must be
86
+ finite" (it gave NaN coefficients with a misleading "coefficient may be infinite").
87
+ - `RNGkind`: a call that gives a kind seeds a generator that was never seeded (from the clock, as a first draw
88
+ would), as R's `RNGkind()` creates `.Random.seed` then; changing only `sampleKind` left it unseeded. A call without
89
+ kinds still leaves it unseeded, as in R.
90
+
91
+ ## 1.2.0 - 2026-11-07
92
+
93
+ Contingency tables and proportions (item 1 of the roadmap): intervals for a proportion and for the risk difference,
94
+ risk ratio and odds ratio of a 2 × 2 table, the mid-p version of Fisher's exact test, Boschloo's test, the G-test,
95
+ the Stuart-Maxwell test, Goodman and Kruskal's gamma, the linear-by-linear association test, the 'N − 1' chi-squared
96
+ test, Freeman-Tukey residuals and equivalence tests, checked against DescTools, epitools, epiR, exact2x2, Exact, coin
97
+ and equivalence (R 4.6.2); where these packages' root searches or maxima are inexact, the true values. `pgamma` (and
98
+ `pchisq`, `ppois`, ...) is more accurate for small shapes and near x = a.
99
+
100
+ ### Added
101
+
102
+ - **Proportions and odds ratios** (one case per call): `binomCI(x, n, { method, confLevel, sides })`, DescTools'
103
+ `BinomCI()`, with the methods `wilson` (default), `wald`, `wilsoncc`, `agresti-coull`, `jeffreys`,
104
+ `clopper-pearson` and `midp`; `binomDiffCI(x1, n1, x2, n2, ...)`, DescTools' `BinomDiffCI()`, with `ac` (default),
105
+ `wald`, `score` (Newcombe's hybrid), `mn` (Miettinen-Nurminen) and `mee` (Farrington-Manning); `binomRatioCI(x1, n1,
106
+ x2, n2, ...)`, DescTools' `BinomRatioCI()`, with `katz.log` (default) and `koopman`; `oddsRatio(table, { method,
107
+ confLevel })`, epitools' `oddsratio()`, with `midp` (default: the median-unbiased estimate and the mid-p exact
108
+ interval), `fisher`, `wald` and `score` (epiR's score interval), and epitools' three p-values. The mid-p and score
109
+ limits are the roots of their equations to the precision of the doubles (the packages stop their searches at 1e-7
110
+ to 1e-3 and fail for zero cells or odds ratios beyond 1000); `binomRatioCI` applies `sides` to the limits; input
111
+ without a defined result is an error (docs/differences-from-r.md). epiR's `epi.2by2` numbers for one stratum are
112
+ reached through these functions.
113
+ - **Mid-p Fisher's exact test**: `fisherTest(x, { midp: true })`, exact2x2's `fisher.exact(midp = TRUE)`, for 2 × 2
114
+ tables: the mid-p p-value (two-sided: the central test) and the mid-p confidence limits as the roots of the mid-p
115
+ tails (exact2x2's search stops up to 1% from them, at 1/eps for large limits); the estimate stays the conditional
116
+ MLE.
117
+ - **Boschloo's test**: `boschlooTest(table, { alternative, tsmethod })`, Exact's `exact.test(method = "boschloo")`,
118
+ for a 2 × 2 table with the groups in the rows: `"square"` (default) or `"central"` two-sided, `alternative` in
119
+ Exact's orientation. The p-value is the true supremum over the nuisance parameter (Exact's is up to 6e-9 below it,
120
+ and its two-sided square region can contain tables that do not belong to it); 200 against 200 takes under 10 ms.
121
+ Tables with more than 2^24 possible outcomes, or a grid that would take more than about 8 s, are a RangeError.
122
+ - **Tests and measures of r × c tables**: `gTest(x, { correct, p, rescaleP })`, DescTools' `GTest()` (independence
123
+ and goodness of fit; corrections `none`, `williams` and `yates` as DescTools; the p-value is the upper tail, where
124
+ DescTools' is 0 below 1.1e-16, and G is summed without cancellation); `stuartMaxwellTest(table)`, DescTools'
125
+ `StuartMaxwellTest()`, with K - 1 degrees of freedom after removing the categories without off-diagonal counts;
126
+ `goodmanKruskalGamma(table, { confLevel })`, DescTools' `GoodmanKruskalGamma()`, with the asymptotic standard error
127
+ ASE1 and the Wald interval; `lblTest(table, { alternative, rowScores, colScores })`, coin's asymptotic `lbl_test()`,
128
+ with scores 1..k for every factor (coin turns the sign for a two-level factor and refuses 2 × 2 tables).
129
+ - **'N - 1' chi-squared test**: `chisqTest(x, { nMinus1: true })` (Campbell 2007; not in R), Pearson's statistic
130
+ without continuity correction times (N - 1)/N, for 2 × 2 and r × c tables.
131
+ - **Freeman-Tukey deviates**: the results of `chisqTest` and `gTest` have `ftResiduals`, `sqrt(O) + sqrt(O + 1) -
132
+ sqrt(4E + 1)` (Bishop, Fienberg and Holland 1975).
133
+ - **Equivalence tests**: `tost(x, y, { epsilon, paired, varEqual, confLevel, alpha })`, equivalence's `tost()`: two
134
+ one-sided t tests (Welch's, pooled or paired, from `tTest`) with the larger p-value and the 1 - 2 alpha interval;
135
+ `binomDiffEquivalenceTest(x1, n1, x2, n2, { margin, method, alpha })` (not in R): equivalence of two proportions on
136
+ counts with the score statistic at -margin and +margin (Miettinen-Nurminen by default, Farrington-Manning `"mee"`,
137
+ `"wald"`), both one-sided p-values, the larger as the p-value, and the dual 1 - 2 alpha interval of `binomDiffCI`.
138
+
139
+ ### Fixed
140
+
141
+ - `pgamma` and `pchisq`: the upper tail for small shapes (a < 4, so df < 8) and 1.1 < x < 64 (in the standardized
142
+ scale) is within a few eps of the true value; it was up to about 120 eps off from the rounding errors of the
143
+ continued fraction, which now runs in double-double there (`pchisq(2.3569217160548437, 1, lowerTail: false)` was
144
+ 45 eps off). The values that depend on it can change in the last bits (for example the p-value of
145
+ `propTrendTest([15, 10, 8, 4], [30, 30, 30, 30])` by one ulp, now correctly rounded). Such calls take up to about
146
+ 8 µs instead of 1 µs.
147
+ - `pgamma` and the functions built on it (`pchisq`, `ppois`, ...) near x = a (20 < a, within Temme's expansion's
148
+ region): within about 4 eps, from up to about 35 eps (`pgamma(256.71, 199, lowerTail: false)` was 22 eps off);
149
+ and with a tiny shape (below 0.01): within a few eps, from up to about 50 eps (`pgamma(100, 1e-100, lowerTail:
150
+ false)`). Values there can change in the last bits.
151
+
10
152
  ## 1.1.0 - 2026-11-06
11
153
 
12
154
  The reference is now R 4.6.2 (until 1.0.0, R 4.5.2): every fixture was regenerated with `oracle/Dockerfile.r46`
package/README.ja.md CHANGED
@@ -16,7 +16,7 @@ JavaScript とブラウザで使える、R と互換の統計関数のライブ
16
16
  - **どこでも動きます。** ESM のみで、依存パッケージはなく、Node 専用の API も使っていません。
17
17
  tree-shaking が効きます (`pnorm` だけなら gzip で 1.6 KB)。
18
18
 
19
- 状態: **1.1.0。** R の stats パッケージの数値計算の中心
19
+ 状態: **1.3.0。** R の stats パッケージの数値計算の中心
20
20
  (分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
21
21
  [ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
22
22
 
@@ -97,6 +97,22 @@ glmAnova(fit).table[1]; // ≈ [1, 62.978, 4, 0.5196,
97
97
  fit.warnings; // [] (収束しないなどの R の警告)
98
98
  ```
99
99
 
100
+ 頑健な共分散 (sandwich の `vcovHC` と `vcovCL`) は、lmtest の `coeftest` と `coefci` に渡せます。修正ポアソン回帰
101
+ (0/1 の結果のポアソン glm) では、リスク比と頑健な信頼区間が得られます。
102
+
103
+ ```ts
104
+ import { glm, vcovHC, coefci } from "@numero-uno-jpn/rstats";
105
+
106
+ const exposed = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
107
+ const event = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
108
+ const fit = glm(exposed, event, { family: "poisson" }); // R: glm(event ~ exposed, family = poisson)
109
+ fit.coefficients.map(Math.exp); // ≈ [0.3, 2] (非曝露のリスク 0.3、リスク比 2)
110
+ const ci = coefci(fit, { vcov: vcovHC(fit, { type: "HC0" }) });
111
+ // R: lmtest::coefci(fit, vcov. = sandwich::vcovHC(fit, type = "HC0"))
112
+ ci.lower.map(Math.exp); // ≈ [0.11640, 0.68361]
113
+ ci.upper.map(Math.exp); // ≈ [0.77320, 5.8513]
114
+ ```
115
+
100
116
  ### formula による分散分析
101
117
 
102
118
  `lm` と `aov` は、R の formula とデータフレーム (列のオブジェクト。文字列の列は因子) でも呼べます。`anova` は R の
@@ -202,12 +218,14 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
202
218
  | 検定 | `tTest`, `chisqTest`, `fisherTest`, `wilcoxTest`, `corTest`, `binomTest`, `poissonTest`, `propTest`, `mcnemarTest`, `varTest`, `bartlettTest`, `kruskalTest`, `friedmanTest`, `quadeTest`, `flignerTest`, `moodTest`, `onewayTest`, `shapiroTest`, `mantelhaenTest`, `ansariTest`, `ksTest`, `pairwiseTTest`, `pairwiseWilcoxTest`, `pairwisePropTest`, `aov` (一元配置。表は当てはめの `aovSummary`), `TukeyHSD`, `zTest`, `brunnerMunzelTest`, `pAdjust` (`p.adjust`) |
203
219
  | 分散分析 | formula で呼ぶ `aov` と `aovSummary` (多元、交互作用、共変量、`Error()` の層), `anova` (`anova.lm`。逐次の表とモデルの比較), `Anova` (car の Type II と III), `aovEz` (afex。反復測定と混合計画、Greenhouse-Geisser と Huynh-Feldt の補正、一般化 η² と偏 η²), `mauchlyTest` (`mauchly.test`) |
204
220
  | 効果量と検出力 | `cohensD`, `hedgesG` (effectsize。信頼区間は厳密な限界), `etaSquared`, `omegaSquared`, `epsilonSquared` (偏・一般化。`anova` と `Anova` の表から), `powerTTest`, `powerPropTest`, `powerAnovaTest` (`power.*.test`), `pwrTTest`, `pwrT2nTest`, `pwr2pTest`, `pwr2p2nTest`, `pwrPTest`, `pwrNormTest`, `pwrRTest`, `pwrChisqTest`, `pwrAnovaTest`, `pwrF2Test`, `esH`, `esW1`, `esW2`, `cohenES` (pwr) |
205
- | 線形モデル | `lm` (formula とデータフレーム、または行列で渡す。`summary` の値も返す), `modelMatrix` (`model.matrix`), `confint`, `predict`。`glm` (行列で渡す形。R の `stats` のすべての族とリンク) と `glmSummary` (`summary.glm`)、`glmResiduals` (4 種類)、`glmHatvalues`、`glmRstandard`、`glmCooksDistance`、`glmPredict` (標準誤差つき)、`glmConfint` (プロファイル尤度、厳密な限界)、`glmAnova` (`anova.glm`) |
221
+ | 線形モデル | `lm` (formula とデータフレーム、または行列で渡す。`summary` の値も返す), `modelMatrix` (`model.matrix`), `confint`, `predict`。`glm` (行列で渡す形。R の `stats` のすべての族とリンク) と `glmSummary` (`summary.glm`)、`glmResiduals` (4 種類)、`glmHatvalues`、`glmRstandard`、`glmCooksDistance`、`glmPredict` (標準誤差つき)、`glmConfint` (プロファイル尤度、厳密な限界)、`glmAnova` (`anova.glm`)。`vcovHC`、`vcovCL` (sandwich: HC0〜HC5、一元と多元のクラスター)、`coeftest`、`coefci` (lmtest) |
206
222
  | 混合モデル | `lmer` (lme4: REML と最尤法、相関のある変量効果と相関のない変量効果、交差と入れ子の群。`fixef`、`vcov`、`VarCorr`、`ranef`、`logLik`、`AIC`、`BIC`、`REMLcrit`、`isSingular`)、`lmerSummary`・`lmerContest`・`lmerAnova` (lmerTest: Satterthwaite の t 検定と F 検定、Type I/II/III の分散分析表。当てはめどうしの尤度比検定)、`glmer` (lme4: glm のすべての族、ラプラス近似と適応的 Gauss-Hermite 求積)、`glmerSummary`・`glmerAnova`・`glmerPredict`・`lmerPredict`。`@numero-uno-jpn/rstats/mixed` から import する |
207
- | ほかの検定 | `leveneTest`、`propTrendTest` (`prop.trend.test`)、`jonckheereTest`、`cochranQTest`、`adTest`、`lillieTest`、`cvmTest`、`sfTest`、`pearsonTest` (car、DescTools、clinfun、nortest) |
223
+ | ほかの検定 | `leveneTest`、`propTrendTest` (`prop.trend.test`)、`jonckheereTest`、`cochranQTest`、`adTest`、`lillieTest`、`cvmTest`、`sfTest`、`pearsonTest` (car、DescTools、clinfun、nortest)。`tTOST`、`tsumTOST` (TOSTER: 平均の同等性検定と最小効果検定) |
224
+ | 分割表と比率 | `binomCI`、`binomDiffCI`、`binomRatioCI` (DescTools の `BinomCI`、`BinomDiffCI`、`BinomRatioCI`)、`oddsRatio` (epitools と epiR のスコア区間)、`fisherTest(x, { midp: true })` (exact2x2)、`boschlooTest` (Exact)、`gTest`、`stuartMaxwellTest`、`goodmanKruskalGamma` (DescTools)、`lblTest` (coin)、`chisqTest(x, { nMinus1: true })` (Campbell の N − 1 検定) と Freeman-Tukey 残差、`tost` (equivalence)、`binomDiffEquivalenceTest` (2 つの比率のスコア法の TOST) |
208
225
  | 多重比較 | `dscfAllPairsTest` (Steel-Dwass)、`kwAllPairsDunnTest`、`kwManyOneDunnTest`、`manyOneUTest` (Steel の多対一の順位検定)、`dunnettTest`、`gamesHowellTest`、`tukeyTest` (PMCMRplus)、`dunnTest` (dunn.test)、`glhtDunnett` (multcomp) |
209
- | 生存時間解析 | `survdiff` (log-rank)、`survfit` (Kaplan-Meier。信頼区間と中央値)、`coxph` (Cox 回帰。Efron と Breslow のタイの扱い、ケースの重み、層、Wald・尤度比・スコア検定) |
210
- | 一致度と信頼性 | `kappa2`、`kappamFleiss`、`icc` (irr)、`cronbachAlpha`、`partialR` (psych)、`polychor`、`polyserial` (polycor)、`pbvnorm`、`factanal`、`omega` (McDonald の ω。psych) |
226
+ | 生存時間解析 | `survdiff` (log-rank)、`survfit` (Kaplan-Meier。信頼区間と中央値)、`coxph` (Cox 回帰。Efron と Breslow のタイの扱い、ケースの重み、層、Wald・尤度比・スコア検定、ロバスト分散と `cluster`) |
227
+ | 診断の精度と測定法の比較 | `roc`、`auc`、`ciAuc` (`ci.auc`)、`rocTest` (`roc.test`)、`coords` (pROC: DeLong の区間と検定、ブートストラップ、部分 AUC)、`diagnosticTests` (epiR の `epi.tests`)、`blandAltman` (BlandAltmanLeh の `bland.altman.stats`)、`mcreg` (mcr: Deming 回帰、重み付き Deming 回帰、Passing-Bablok 回帰) |
228
+ | 一致度と信頼性 | `kappa2`、`kappamFleiss`、`icc` (irr)、`ICC` (psych: Shrout と Fleiss の 6 つの形式)、`cronbachAlpha`、`partialR` (psych)、`polychor`、`polyserial` (polycor)、`pbvnorm`、`factanal`、`omega` (McDonald の ω。psych) |
211
229
  | データの扱い | `completeCases` (`complete.cases`)、`naOmit` (`na.omit`)、`subset`、`merge`、データフレームの `rbind`・`cbind`、`tapply`、`split`、`aggregate`、`pivotLonger` と `pivotWider` (tidyr)、`fromRows` と `toRows` (行のオブジェクトの配列とデータフレームの相互の変換)。検定の formula 版 (`tTest("y ~ g", data)`、`kruskalTest`、`friedmanTest("y ~ w \| b", data)`、`corTest("~ x + y", data)` など) |
212
230
  | 線形代数 | `matMul` (`%*%`), `add`, `subtract`, `multiply`, `divide`, `outer`, `t`, `diag`, `cbind`, `rbind`, `matrix`, `kronecker`, `seq`, `crossprod`, `tcrossprod`, `norm`, `backsolve`, `forwardsolve`, `chol`, `chol2inv`, `qr` と `qrQ`, `qrR`, `qrX`, `qrCoef`, `qrQy`, `qrQty`, `qrResid`, `qrFitted`, `qrSolve` (`qr.Q` …), `solve`, `det`, `determinant`, `rcond`, `kappa`, `svd`, `eigen`, `lu`, `prcomp`, `ginv` (MASS)、`schur`、`expm` |
213
231
  | 数値計算 | `integrate`, `optimize`, `optim`, `optimHess`, `uniroot`, `approx`, `spline`, `splinefun`, `splinefunH`, `barylag`, `hermiteInterp`, `ode`, `grad`, `jacobian`, `hessian` |
@@ -216,7 +234,7 @@ R の分析の書き方 (データフレーム、formula、因子) に慣れて
216
234
 
217
235
  jStat から移るときは [docs/ja/migrating-from-jstat.md](docs/ja/migrating-from-jstat.md) に jStat の全関数の置き換えがあります。
218
236
 
219
- [API リファレンス](https://numero-uno-jpn.github.io/rStats.js/api/) (英語) に、すべての関数の説明と使用例があります (使用例はテストで実行しています)。
237
+ [API リファレンス](https://numero-uno-jpn.github.io/rStats.js/ja/api/) に、すべての関数の説明と使用例があります (使用例はテストで実行しています)。
220
238
  R の関数から rStats.js の関数を引くには [docs/ja/r-functions.md](docs/ja/r-functions.md) を見てください。(`npm run docs` で手元でもリファレンスを作れます。)
221
239
 
222
240
  AI のコーディング支援向けに、R のコードを rStats.js の呼び出しに書き換える方法を [llms.txt](llms.txt)
@@ -267,12 +285,12 @@ double-double 演算で計算しているためです。詳しくは [docs/ja/ac
267
285
  | `pnorm` | 1.6 KB |
268
286
  | `setSeed`, `rnorm` | 2.0 KB |
269
287
  | `solve` / `svd` / `eigen` | 2.4 / 2.4 / 5.1 KB |
270
- | `wilcoxTest` / `fisherTest` / `tTest` | 18.9 / 27.7 / 31.0 KB |
271
- | `qbeta` / `pt` と `qt` | 43.5 / 40.0 KB |
272
- | `glm` と `glmSummary` / `glm` とそのすべての関数 | 35.0 / 51.0 KB |
273
- | `lmer` (`/mixed` から) / `lmerSummary`・`lmerContest`・`lmerAnova` も | 19.4 / 69.6 KB |
274
- | `glmer` (`/mixed` から) / `glmerSummary`・`glmerAnova`・`glmerPredict` も | 47.2 / 65.7 KB |
275
- | すべて (`/mixed` を除く) | 251.5 KB |
288
+ | `wilcoxTest` / `fisherTest` / `tTest` | 18.9 / 27.9 / 31.0 KB |
289
+ | `qbeta` / `pt` と `qt` | 43.9 / 40.4 KB |
290
+ | `glm` と `glmSummary` / `glm` とそのすべての関数 | 35.0 / 51.4 KB |
291
+ | `lmer` (`/mixed` から) / `lmerSummary`・`lmerContest`・`lmerAnova` も | 19.4 / 70.0 KB |
292
+ | `glmer` (`/mixed` から) / `glmerSummary`・`glmerAnova`・`glmerPredict` も | 47.2 / 66.1 KB |
293
+ | すべて (`/mixed` を除く) | 289.5 KB |
276
294
 
277
295
  (`npm run size` で測れます。)
278
296
 
@@ -282,12 +300,12 @@ double-double 演算で計算しているためです。詳しくは [docs/ja/ac
282
300
  できません。メインの入口には含めていません)。
283
301
 
284
302
  バンドラを使わない場合は、1 ファイルにまとめたビルド `dist/rstats.js` (`/mixed` 以外のすべての関数を含む
285
- minify 済みの ES モジュール、gzip で 249 KB) を jsDelivr から読み込めます。jsDelivr は、npm のリリースを
303
+ minify 済みの ES モジュール、gzip で 290 KB) を jsDelivr から読み込めます。jsDelivr は、npm のリリースを
286
304
  そのまま配信します。
287
305
 
288
306
  ```html
289
307
  <script type="module">
290
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.1.0/dist/rstats.js";
308
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.3.0/dist/rstats.js";
291
309
  console.log(pnorm(1.96)); // ≈ 0.9750021049
292
310
  </script>
293
311
  ```
@@ -303,7 +321,7 @@ minify 済みの ES モジュール、gzip で 249 KB) を jsDelivr から読み
303
321
  `dist/tests.js`、`dist/linalg.js`、`dist/descriptive.js`、`dist/numerics.js`、`dist/special.js`、
304
322
  `dist/mixed.js` は上のサブパスと同じ関数を export し、共通のコードを `dist/chunks/` で共有します。そのため、
305
323
  2 つの分野を読み込んでも共通部分は 1 回しか読み込まれません。chunk を含めた 1 分野の転送量は、gzip で
306
- 38 KB (`special`) から 206 KB (`tests`) です。
324
+ 39 KB (`special`) から 250 KB (`tests`) です。
307
325
 
308
326
  1 つのページでは、`dist/rstats.js` か分野ごとのバンドルのどちらか一方だけを使ってください。両者は別々の
309
327
  モジュールの集まりなので、混ぜると共通のコードが 2 回読み込まれ、乱数の状態も 2 つになります (一方の `setSeed`
package/README.md CHANGED
@@ -14,7 +14,7 @@ R-compatible statistical functions for JavaScript and the browser, written in Ty
14
14
  - **Runs anywhere.** ESM only, no dependencies, no Node-specific APIs, tree-shakable
15
15
  (`pnorm` alone is 1.6 KB gzipped).
16
16
 
17
- Status: **1.1.0.** The goal is to cover the numerical core of R's
17
+ Status: **1.3.0.** The goal is to cover the numerical core of R's
18
18
  `stats` package (distributions, descriptive statistics, hypothesis tests, linear models, special
19
19
  functions, numerical methods and the basics of linear algebra) with R-compatible results; see [ROADMAP.md](ROADMAP.md) for what remains. See [CHANGELOG.md](CHANGELOG.md).
20
20
 
@@ -93,6 +93,22 @@ glmAnova(fit).table[1]; // ≈ [1, 62.978, 4, 0.5196,
93
93
  fit.warnings; // [] (R's warnings, such as non-convergence)
94
94
  ```
95
95
 
96
+ Robust covariances (sandwich's `vcovHC` and `vcovCL`) go into lmtest's `coeftest` and `coefci`. A modified Poisson
97
+ regression (a Poisson glm of a 0/1 outcome) gives a risk ratio with a robust interval:
98
+
99
+ ```ts
100
+ import { glm, vcovHC, coefci } from "@numero-uno-jpn/rstats";
101
+
102
+ const exposed = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
103
+ const event = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
104
+ const fit = glm(exposed, event, { family: "poisson" }); // R: glm(event ~ exposed, family = poisson)
105
+ fit.coefficients.map(Math.exp); // ≈ [0.3, 2] (risk 0.3 unexposed; risk ratio 2)
106
+ const ci = coefci(fit, { vcov: vcovHC(fit, { type: "HC0" }) });
107
+ // R: lmtest::coefci(fit, vcov. = sandwich::vcovHC(fit, type = "HC0"))
108
+ ci.lower.map(Math.exp); // ≈ [0.11640, 0.68361]
109
+ ci.upper.map(Math.exp); // ≈ [0.77320, 5.8513]
110
+ ```
111
+
96
112
  ### Analysis of variance with formulas
97
113
 
98
114
  `lm` and `aov` also take an R formula and a data frame (an object of columns; strings are factors). `anova` gives
@@ -200,12 +216,14 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
200
216
  | Hypothesis tests | `tTest`, `chisqTest`, `fisherTest`, `wilcoxTest`, `corTest`, `binomTest`, `poissonTest`, `propTest`, `mcnemarTest`, `varTest`, `bartlettTest`, `kruskalTest`, `friedmanTest`, `quadeTest`, `flignerTest`, `moodTest`, `onewayTest`, `shapiroTest`, `mantelhaenTest`, `ansariTest`, `ksTest`, `pairwiseTTest`, `pairwiseWilcoxTest`, `pairwisePropTest`, `aov` (one way, a fit whose table is `aovSummary`), `TukeyHSD`, `zTest`, `brunnerMunzelTest`, `pAdjust` (`p.adjust`) |
201
217
  | Analysis of variance | `aov` and `aovSummary` with a formula (several factors, interactions, covariates, `Error()` strata), `anova` (`anova.lm`, sequential and model comparison), `Anova` (car: types II and III), `aovEz` (afex: repeated-measures and mixed designs, Greenhouse-Geisser and Huynh-Feldt corrections, generalized and partial eta squared), `mauchlyTest` (`mauchly.test`) |
202
218
  | Effect sizes and power | `cohensD`, `hedgesG` (effectsize, with exact confidence limits), `etaSquared`, `omegaSquared`, `epsilonSquared` (partial, generalized, from `anova` and `Anova` tables); `powerTTest`, `powerPropTest`, `powerAnovaTest` (`power.*.test`); `pwrTTest`, `pwrT2nTest`, `pwr2pTest`, `pwr2p2nTest`, `pwrPTest`, `pwrNormTest`, `pwrRTest`, `pwrChisqTest`, `pwrAnovaTest`, `pwrF2Test`, `esH`, `esW1`, `esW2`, `cohenES` (pwr) |
203
- | Linear models | `lm` (a formula and a data frame, or a matrix, with the `summary` quantities), `modelMatrix` (`model.matrix`), `confint`, `predict`; `glm` (matrix interface, every family and link of R's `stats`) with `glmSummary` (`summary.glm`), `glmResiduals` (the four kinds), `glmHatvalues`, `glmRstandard`, `glmCooksDistance`, `glmPredict` (with standard errors), `glmConfint` (profile likelihood, exact limits), `glmAnova` (`anova.glm`) |
219
+ | Linear models | `lm` (a formula and a data frame, or a matrix, with the `summary` quantities), `modelMatrix` (`model.matrix`), `confint`, `predict`; `glm` (matrix interface, every family and link of R's `stats`) with `glmSummary` (`summary.glm`), `glmResiduals` (the four kinds), `glmHatvalues`, `glmRstandard`, `glmCooksDistance`, `glmPredict` (with standard errors), `glmConfint` (profile likelihood, exact limits), `glmAnova` (`anova.glm`); `vcovHC`, `vcovCL` (sandwich: HC0 to HC5, one-way and multi-way clustered), `coeftest`, `coefci` (lmtest) |
204
220
  | Mixed models | `lmer` (lme4: REML and ML, correlated and uncorrelated random effects, crossed and nested grouping factors; `fixef`, `vcov`, `VarCorr`, `ranef`, `logLik`, `AIC`, `BIC`, `REMLcrit`, `isSingular`), `lmerSummary`, `lmerContest` and `lmerAnova` (lmerTest: Satterthwaite's t- and F-tests, Type I/II/III ANOVA tables; likelihood-ratio comparison of fits), `glmer` (lme4: all glm families, Laplace approximation and adaptive Gauss-Hermite quadrature), `glmerSummary`, `glmerAnova`, `glmerPredict` and `lmerPredict`, from `@numero-uno-jpn/rstats/mixed` |
205
- | More tests | `leveneTest`, `propTrendTest` (`prop.trend.test`), `jonckheereTest`, `cochranQTest`, `adTest`, `lillieTest`, `cvmTest`, `sfTest`, `pearsonTest` (car, DescTools, clinfun, nortest) |
221
+ | More tests | `leveneTest`, `propTrendTest` (`prop.trend.test`), `jonckheereTest`, `cochranQTest`, `adTest`, `lillieTest`, `cvmTest`, `sfTest`, `pearsonTest` (car, DescTools, clinfun, nortest); `tTOST`, `tsumTOST` (TOSTER: equivalence and minimal-effect t tests) |
222
+ | Contingency tables and proportions | `binomCI`, `binomDiffCI`, `binomRatioCI` (DescTools' `BinomCI`, `BinomDiffCI`, `BinomRatioCI`), `oddsRatio` (epitools, and epiR's score interval), `fisherTest(x, { midp: true })` (exact2x2), `boschlooTest` (Exact), `gTest`, `stuartMaxwellTest`, `goodmanKruskalGamma` (DescTools), `lblTest` (coin), `chisqTest(x, { nMinus1: true })` (Campbell's 'N − 1' test) and Freeman-Tukey residuals, `tost` (equivalence), `binomDiffEquivalenceTest` (score TOST of two proportions) |
206
223
  | Multiple comparisons | `dscfAllPairsTest` (Steel-Dwass), `kwAllPairsDunnTest`, `kwManyOneDunnTest`, `manyOneUTest` (Steel's many-one rank test), `dunnettTest`, `gamesHowellTest`, `tukeyTest` (PMCMRplus), `dunnTest` (dunn.test), `glhtDunnett` (multcomp) |
207
- | Survival analysis | `survdiff` (log-rank), `survfit` (Kaplan-Meier with intervals and median), `coxph` (Cox regression: Efron and Breslow ties, case weights, strata, the Wald, likelihood-ratio and score tests) |
208
- | Agreement and reliability | `kappa2`, `kappamFleiss`, `icc` (irr), `cronbachAlpha`, `partialR` (psych), `polychor`, `polyserial` (polycor), `pbvnorm`, `factanal`, `omega` (McDonald's ω, psych) |
224
+ | Survival analysis | `survdiff` (log-rank), `survfit` (Kaplan-Meier with intervals and median), `coxph` (Cox regression: Efron and Breslow ties, case weights, strata, the Wald, likelihood-ratio and score tests, the robust variance and `cluster`) |
225
+ | Diagnostic accuracy and method comparison | `roc`, `auc`, `ciAuc` (`ci.auc`), `rocTest` (`roc.test`), `coords` (pROC: DeLong's interval and test, the bootstrap, partial AUC), `diagnosticTests` (epiR's `epi.tests`), `blandAltman` (BlandAltmanLeh's `bland.altman.stats`), `mcreg` (mcr: Deming, weighted Deming and Passing-Bablok regression) |
226
+ | Agreement and reliability | `kappa2`, `kappamFleiss`, `icc` (irr), `ICC` (psych: the six forms of Shrout and Fleiss), `cronbachAlpha`, `partialR` (psych), `polychor`, `polyserial` (polycor), `pbvnorm`, `factanal`, `omega` (McDonald's ω, psych) |
209
227
  | Data handling | `completeCases` (`complete.cases`), `naOmit` (`na.omit`), `subset`, `merge`, `rbind` and `cbind` of data frames, `tapply`, `split`, `aggregate`, `pivotLonger` and `pivotWider` (tidyr), `fromRows` and `toRows` (a data frame from an array of row objects and back); formula forms of the tests (`tTest("y ~ g", data)`, `kruskalTest`, `friedmanTest("y ~ w \| b", data)`, `corTest("~ x + y", data)`, ...) |
210
228
  | Linear algebra | `matMul` (`%*%`), `add`, `subtract`, `multiply`, `divide`, `outer`, `t`, `diag`, `cbind`, `rbind`, `matrix`, `kronecker`, `seq`, `crossprod`, `tcrossprod`, `norm`, `backsolve`, `forwardsolve`, `chol`, `chol2inv`, `qr` with `qrQ`, `qrR`, `qrX`, `qrCoef`, `qrQy`, `qrQty`, `qrResid`, `qrFitted`, `qrSolve` (`qr.Q` …), `solve`, `det`, `determinant`, `rcond`, `kappa`, `svd`, `eigen`, `lu`, `prcomp`, `ginv` (MASS), `schur`, `expm` |
211
229
  | Numerical methods | `integrate`, `optimize`, `optim`, `optimHess`, `uniroot`, `approx`, `spline`, `splinefun`, `splinefunH`, `barylag`, `hermiteInterp`, `ode`, `grad`, `jacobian`, `hessian` |
@@ -266,12 +284,12 @@ removed. Approximate sizes after minification and gzip:
266
284
  | `pnorm` | 1.6 KB |
267
285
  | `setSeed`, `rnorm` | 2.0 KB |
268
286
  | `solve` / `svd` / `eigen` | 2.4 / 2.4 / 5.1 KB |
269
- | `wilcoxTest` / `fisherTest` / `tTest` | 18.9 / 27.7 / 31.0 KB |
270
- | `qbeta` / `pt` and `qt` | 43.5 / 40.0 KB |
271
- | `glm` and `glmSummary` / `glm` with all its methods | 35.0 / 51.0 KB |
272
- | `lmer` (from `/mixed`) / with `lmerSummary`, `lmerContest`, `lmerAnova` | 19.4 / 69.6 KB |
273
- | `glmer` (from `/mixed`) / with `glmerSummary`, `glmerAnova`, `glmerPredict` | 47.2 / 65.7 KB |
274
- | everything (except `/mixed`) | 251.5 KB |
287
+ | `wilcoxTest` / `fisherTest` / `tTest` | 18.9 / 27.9 / 31.0 KB |
288
+ | `qbeta` / `pt` and `qt` | 43.9 / 40.4 KB |
289
+ | `glm` and `glmSummary` / `glm` with all its methods | 35.0 / 51.4 KB |
290
+ | `lmer` (from `/mixed`) / with `lmerSummary`, `lmerContest`, `lmerAnova` | 19.4 / 70.0 KB |
291
+ | `glmer` (from `/mixed`) / with `glmerSummary`, `glmerAnova`, `glmerPredict` | 47.2 / 66.1 KB |
292
+ | everything (except `/mixed`) | 289.5 KB |
275
293
 
276
294
  (`npm run size` measures these.)
277
295
 
@@ -281,11 +299,11 @@ Each area is also a subpath export, for importing one area without the rest:
281
299
  (`lmer`, `glmer` and their methods; this area is only available this way, not from the main entry point).
282
300
 
283
301
  Without a bundler, load the single-file build `dist/rstats.js` (one minified ES module with every
284
- function except those of `/mixed`, 249 KB gzipped) from jsDelivr, which serves each npm release:
302
+ function except those of `/mixed`, 290 KB gzipped) from jsDelivr, which serves each npm release:
285
303
 
286
304
  ```html
287
305
  <script type="module">
288
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.1.0/dist/rstats.js";
306
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.3.0/dist/rstats.js";
289
307
  console.log(pnorm(1.96)); // ≈ 0.9750021049
290
308
  </script>
291
309
  ```
@@ -301,7 +319,7 @@ A page that needs only some areas can load the per-area bundles instead: `dist/d
301
319
  `dist/tests.js`, `dist/linalg.js`, `dist/descriptive.js`, `dist/numerics.js`, `dist/special.js` and
302
320
  `dist/mixed.js` export the same functions as the subpaths above, and share their common code through
303
321
  `dist/chunks/`, so loading two areas does not load that code twice. With its chunks, one area
304
- transfers 38 KB (`special`) to 206 KB (`tests`) gzipped.
322
+ transfers 39 KB (`special`) to 250 KB (`tests`) gzipped.
305
323
 
306
324
  Use either `dist/rstats.js` or the per-area bundles on one page, not both: they are separate sets of modules, so a
307
325
  page that mixes them loads the common code twice and has two random number states (`setSeed` from one does not seed
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.1.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{G as i,l as n,z as t}from"./chunk-NDTJ23A6.js";function o(r){return Number.isNaN(r)||r<-1?NaN:r===-1||r===1/0?-1/0:i(r)}function a(r){return Number.isNaN(r)||r===-1/0?NaN:r===1/0||r<=-1&&r===Math.floor(r)?1/0:t(r)}function m(r){return Number.isNaN(r)||r<0?NaN:r===0?-1/0:r===1/0?0:n(-r)}function p(r){return Number.isNaN(r)?NaN:r<=-37?Math.exp(r):r<=18?Math.log1p(Math.exp(r)):r<=33.3?r+Math.exp(-r):r}export{o as a,a as b,m as c,p as d};
1
+ /*! rStats.js 1.3.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{G as i,l as n,z as t}from"./chunk-P7ZHH2SF.js";function o(r){return Number.isNaN(r)||r<-1?NaN:r===-1||r===1/0?-1/0:i(r)}function a(r){return Number.isNaN(r)||r===-1/0?NaN:r===1/0||r<=-1&&r===Math.floor(r)?1/0:t(r)}function m(r){return Number.isNaN(r)||r<0?NaN:r===0?-1/0:r===1/0?0:n(-r)}function p(r){return Number.isNaN(r)?NaN:r<=-37?Math.exp(r):r<=18?Math.log1p(Math.exp(r)):r<=33.3?r+Math.exp(-r):r}export{o as a,a as b,m as c,p as d};
@@ -0,0 +1,2 @@
1
+ /*! rStats.js 1.3.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{I as p,P as S,g as A,l,n as b,o as _,r as v,s as y,t as I,u as w,w as F,x as E,y as D,z as K}from"./chunk-PDHBRDTF.js";var G=["naRm"],T=["naRm"],U=["trim","naRm"],V=["naRm"],W=["naRm"],j=["naRm"],q=["naRm"],C=["naRm"],H=["lag","differences"];function h(i,t){let n=Array.from(i);return t?n.filter(e=>!Number.isNaN(e)):n.some(Number.isNaN)?void 0:n}function $(i,t={}){l(t,G,"sum");let n=h(i,t.naRm);return n===void 0?NaN:p(n)}function nn(i,t={}){l(t,T,"prod");let n=h(i,t.naRm);if(n===void 0)return NaN;let e=Y();for(let r=0;r<n.length;r++){let o=n[r];if(!Number.isFinite(o)||o===0)return n.slice(r).reduce((a,u)=>a*u,k(e));O(e,o)}return B(e.p,e.e)}function Y(){return{p:[1,0],e:0}}function O(i,t){let n=Math.floor(Math.log2(Math.abs(t)));(n>500||n<-500)&&(t=w(t,-n),i.e+=n);let e=A(i.p,[t,0]);if(n=Math.floor(Math.log2(Math.abs(e[0]))),n>500||n<-500){let r=2**-n;e=[e[0]*r,e[1]*r],i.e+=n}i.p=e}function k(i){return i.p[0]<0?-1:1}function en(i,t={}){l(t,U,"mean");let n=h(i,t.naRm),e=t.trim??0;if(Number.isNaN(e)&&(n===void 0||n.length>0))throw new RangeError("'trim' must be numeric of length one");if(n===void 0)return NaN;let r=n.length;if(r===0)return NaN;if(e>0&&r>0){if(e>=.5)return J(n);e=Math.max(e,0);let o=Math.floor(r*e),a=[...n].sort((u,N)=>u-N);return E(a.slice(o,r-o))}return E(n)}function tn(i,t,n={}){l(n,V,"weightedMean");let e=Array.from(i),r=Array.from(t);if(e.length!==r.length)throw new RangeError("'x' and 'w' must have the same length");if(n.naRm){let s=e.map(f=>!Number.isNaN(f));e=e.filter((f,d)=>s[d]),r=r.filter((f,d)=>s[d])}let o=[],a=!1;for(let s=0;s<e.length;s++){if(r[s]===0)continue;let f=e[s]*r[s];e[s]!==0&&Math.abs(f)<2**-1022&&(a=!0),o.push(f)}let u=p(r),N=p(o)/u;if(Number.isFinite(N)&&Number.isFinite(u)&&!a||!e.every(Number.isFinite)||!r.every(Number.isFinite))return N;let x=z(e,r);if(x!==void 0)return x;let M=e.filter((s,f)=>r[f]!==0),{groups:[R],k:g}=S([M]),{groups:[c]}=S([r]),m=[];for(let s=0,f=0;s<e.length;s++)r[s]!==0&&m.push(R[f++]*c[s]);return w(p(m)/p(c),g)}function z(i,t){let n=[],e=[];for(let c=0;c<i.length;c++){if(t[c]===0)continue;let[m,s]=b(t[c]);if(e.push([m,s]),i[c]===0)continue;let[f,d]=b(i[c]);n.push([f*m,d+s])}let r=c=>{let m=0;for(let[,f]of c)m=Math.min(m,f);let s=0n;for(let[f,d]of c)s+=f<<BigInt(d-m);return[s,m]},[o,a]=r(n),[u,N]=r(e);if(u===0n)return;if(o===0n)return 0;u<0n&&(o=-o,u=-u);let x=o<0n,M=x?-o:o,R=Math.max(0,u.toString(2).length-M.toString(2).length+66),g=(M<<BigInt(R))/u;return g*u!==M<<BigInt(R)&&(g|=1n),_(x?-g:g,a-N-R)}function rn(i,t={}){l(t,W,"variance");let n=h(i,t.naRm);return n===void 0?NaN:D(n)}function on(i,t={}){l(t,j,"sd");let n=h(i,t.naRm);return n===void 0?NaN:K(n)}function J(i,t={}){l(t,q,"median");let n=h(i,t.naRm);if(n===void 0)return NaN;let e=n.length;if(e===0)return NaN;let r=[...n].sort((a,u)=>a-u),o=Math.floor(e/2);return e%2===1?r[o]:F([r[o-1],r[o]])[0]}function un(i,t={}){l(t,C,"range");let n=h(i,t.naRm);if(n===void 0)return[NaN,NaN];let e=1/0,r=-1/0;for(let o of n)o<e&&(e=o),o>r&&(r=o);return[e,r]}function sn(i){let t=Array.from(i),n=[],e=v(),r;for(let o of t){if(r===void 0&&!Number.isFinite(o)&&(r=0),r!==void 0){r+=o,n.push(r);continue}y(e,o,t.length),n.push(I(e))}return n}function fn(i){let t=[],n=Y(),e;for(let r of Array.from(i)){if(e===void 0&&(!Number.isFinite(r)||r===0)&&(e=k(n)),e!==void 0){e*=r,t.push(e);continue}O(n,r),t.push(B(n.p,n.e))}return t}function B(i,t){let n=i[0]+i[1];for(;t>0&&Number.isFinite(n);){let e=Math.min(t,1e3);n*=2**e,t-=e}for(;t<0&&n!==0;){let e=Math.max(t,-1e3);n*=2**e,t-=e}return n}function P(i,t){let n=[],e=NaN,r=!1;for(let o of Array.from(i)){if(r||Number.isNaN(o)){r=!0,n.push(NaN);continue}(n.length===0||t(o,e))&&(e=o),n.push(e)}return n}function an(i){return P(i,(t,n)=>t>n)}function cn(i){return P(i,(t,n)=>t<n)}function mn(i,t={}){l(t,H,"diff");let n=t.lag??1,e=t.differences??1;if(!(Number.isInteger(n)&&n>=1&&Number.isInteger(e)&&e>=1))throw new RangeError("'lag' and 'differences' must be integers >= 1");let r=Array.from(i);if(n*e>=r.length)return[];for(let o=0;o<e;o++){let a=[];for(let u=n;u<r.length;u++)a.push(r[u]-r[u-n]);r=a}return r}export{h as a,$ as b,nn as c,en as d,tn as e,rn as f,on as g,J as h,un as i,sn as j,fn as k,an as l,cn as m,mn as n};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.1.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{f as N,i as b,j as a}from"./chunk-QUTJEYDX.js";import{f as l}from"./chunk-NDTJ23A6.js";import{d as f,h as m,k as c,l as u}from"./chunk-HUWOSLKE.js";function o(n,t){if(!Number.isFinite(n)||n<0)throw new RangeError("n must be a non-negative finite number");let e=Math.trunc(n),r=new Array(e);for(let i=0;i<e;i++)r[i]=t();return r}function h(n,t){let e=1;if(Number.isNaN(n))return n;if(t!==0){if(!Number.isFinite(n))return Math.pow(n,t);for(t<0&&(t=-t,n=1/n);t&1&&(e*=n),t>>=1,t;)n*=n}return e}var p=["min","max"],d=["mean","sd"],g=["rate"],R=["meanlog","sdlog"],E=["location","scale"],M=["location","scale"],x=["scale"];function y(n,t={}){u(t,p,"runif");let{min:e=0,max:r=1}=t;return o(n,()=>{if(!Number.isFinite(e)||!Number.isFinite(r)||r<e)return NaN;if(e===r)return e;let i=N();return Number.isFinite(r-e)?e+(r-e)*i:e*(1-i)+r*i})}function F(n,t){if(Number.isNaN(n)||!Number.isFinite(t)||t<0)return NaN;if(t===0||!Number.isFinite(n))return n;let e=b(),r=n+t*e;return Number.isFinite(r)?r:2*(n/2+t/2*e)}function L(n,t={}){u(t,d,"rnorm");let{mean:e=0,sd:r=1}=t;return o(n,()=>F(e,r))}function O(n,t={}){u(t,g,"rexp");let e=t.rate??1,r=1/e;return o(n,()=>r===1/0&&e>0?a()/e:!Number.isFinite(r)||r<=0?r===0?0:NaN:r*a())}function A(n,t={}){u(t,R,"rlnorm");let{meanlog:e=0,sdlog:r=1}=t;return o(n,()=>Number.isNaN(e)||!Number.isFinite(r)||r<0?NaN:Math.exp(F(e,r)))}function U(n,t={}){u(t,E,"rlogis");let{location:e=0,scale:r=1}=t;return o(n,()=>{if(Number.isNaN(e)||!Number.isFinite(r))return NaN;if(r<0)return N(),NaN;if(r===0||!Number.isFinite(e))return e;let i=N();return e+r*Math.log(i/(1-i))})}function k(n,t={}){u(t,M,"rcauchy");let{location:e=0,scale:r=1}=t;return o(n,()=>Number.isNaN(e)||!Number.isFinite(r)||r<0?NaN:r===0||!Number.isFinite(e)?e:e+r*Math.tan(Math.PI*N()))}function C(n,t,e={}){u(e,x,"rweibull");let{scale:r=1}=e;return o(n,()=>{if(!(t>0)||!(r>=0))return NaN;if(!Number.isFinite(t)||!Number.isFinite(r)||r===0)return r===0?0:NaN;let i=-Math.log(N()),s=Math.pow(i,1/t);return s!==1/0?r*s:l(f(c([r,0]),m(c([i,0]),1/t)))[0]})}export{o as a,h as b,y as c,F as d,L as e,O as f,A as g,U as h,k as i,C as j};
1
+ /*! rStats.js 1.3.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{g as N,j as b,k as a}from"./chunk-TZTVDVP4.js";import{f as l}from"./chunk-P7ZHH2SF.js";import{d as f,h as m,k as c,l as u}from"./chunk-PDHBRDTF.js";function o(n,t){if(!Number.isFinite(n)||n<0)throw new RangeError("n must be a non-negative finite number");let e=Math.trunc(n),r=new Array(e);for(let i=0;i<e;i++)r[i]=t();return r}function h(n,t){let e=1;if(Number.isNaN(n))return n;if(t!==0){if(!Number.isFinite(n))return Math.pow(n,t);for(t<0&&(t=-t,n=1/n);t&1&&(e*=n),t>>=1,t;)n*=n}return e}var p=["min","max"],d=["mean","sd"],g=["rate"],R=["meanlog","sdlog"],E=["location","scale"],M=["location","scale"],x=["scale"];function y(n,t={}){u(t,p,"runif");let{min:e=0,max:r=1}=t;return o(n,()=>{if(!Number.isFinite(e)||!Number.isFinite(r)||r<e)return NaN;if(e===r)return e;let i=N();return Number.isFinite(r-e)?e+(r-e)*i:e*(1-i)+r*i})}function F(n,t){if(Number.isNaN(n)||!Number.isFinite(t)||t<0)return NaN;if(t===0||!Number.isFinite(n))return n;let e=b(),r=n+t*e;return Number.isFinite(r)?r:2*(n/2+t/2*e)}function L(n,t={}){u(t,d,"rnorm");let{mean:e=0,sd:r=1}=t;return o(n,()=>F(e,r))}function O(n,t={}){u(t,g,"rexp");let e=t.rate??1,r=1/e;return o(n,()=>r===1/0&&e>0?a()/e:!Number.isFinite(r)||r<=0?r===0?0:NaN:r*a())}function A(n,t={}){u(t,R,"rlnorm");let{meanlog:e=0,sdlog:r=1}=t;return o(n,()=>Number.isNaN(e)||!Number.isFinite(r)||r<0?NaN:Math.exp(F(e,r)))}function U(n,t={}){u(t,E,"rlogis");let{location:e=0,scale:r=1}=t;return o(n,()=>{if(Number.isNaN(e)||!Number.isFinite(r))return NaN;if(r<0)return N(),NaN;if(r===0||!Number.isFinite(e))return e;let i=N();return e+r*Math.log(i/(1-i))})}function k(n,t={}){u(t,M,"rcauchy");let{location:e=0,scale:r=1}=t;return o(n,()=>Number.isNaN(e)||!Number.isFinite(r)||r<0?NaN:r===0||!Number.isFinite(e)?e:e+r*Math.tan(Math.PI*N()))}function C(n,t,e={}){u(e,x,"rweibull");let{scale:r=1}=e;return o(n,()=>{if(!(t>0)||!(r>=0))return NaN;if(!Number.isFinite(t)||!Number.isFinite(r)||r===0)return r===0?0:NaN;let i=-Math.log(N()),s=Math.pow(i,1/t);return s!==1/0?r*s:l(f(c([r,0]),m(c([i,0]),1/t)))[0]})}export{o as a,h as b,y as c,F as d,L as e,O as f,A as g,U as h,k as i,C as j};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.1.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{b as A}from"./chunk-EJYCDE4Z.js";var y=t=>new SyntaxError(`invalid formula: ${t}`),L=/^(?:[\p{L}\p{Nl}.]|(?![0-9])\p{Nd})[\p{L}\p{Nl}\p{Nd}\p{M}._]*/u;function R(t,u,i=!1){let a=[],n=0;for(;n<t.length;){let e=t[n];if(/\s/.test(e)){n++;continue}if(/[0-9]/.test(e)||e==="."&&/[0-9]/.test(t[n+1]??"")){let c=/^(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(t.slice(n));a.push({kind:"num",text:c[0]}),n+=c[0].length;continue}let r=L.exec(t.slice(n));if(r!==null){a.push({kind:"name",text:r[0]}),n+=r[0].length;continue}if(t.startsWith("%in%",n)){a.push({kind:"op",text:"%in%"}),n+=4;continue}if(u&&e==="|"){let c=t[n+1]==="|"?"||":"|";a.push({kind:"op",text:c}),n+=c.length;continue}if("~+-*/:^()".includes(e)||i&&e===","){a.push({kind:"op",text:e}),n++;continue}throw y(`unexpected '${e}'`)}return a.push({kind:"end"}),a}var T={"|":.5,"||":.5,"+":1,"-":1,"*":2,"/":2,"%in%":3,":":4,"^":6},C=5;function I(t,u=!1,i=!1,a=!1){if(typeof t!="string")throw new TypeError("the formula must be a string");let n=R(t,i,a),e=0,r=()=>n[e],c=()=>n[e++],f=(o,d)=>o.kind==="op"&&o.text===d;function m(){let o=c();if(o.kind==="name"){if(f(r(),"(")){if(o.text!=="Error"||!u)throw y(`function calls are not supported (${o.text})`);c();let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"Error",arg:d}}if(o.text===".")return{type:"dot"};if(/^\.[0-9]/.test(o.text))throw y(`unexpected '${o.text}'`);return{type:"var",name:o.text}}if(o.kind==="num")return{type:"num",value:Number(o.text),text:o.text};if(o.kind==="op"&&o.text==="("){let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"paren",arg:d}}if(o.kind==="op"&&(o.text==="-"||o.text==="+"))return{type:"unary",op:o.text,arg:g(C)};throw y(o.kind==="end"?"unexpected end of input":`unexpected '${o.kind==="op"?o.text:""}'`)}function g(o){let d=m();for(;;){let x=r();if(x.kind!=="op")break;let h=T[x.text];if(h===void 0||h<=o)break;c();let v=g(x.text==="^"?h-1:h);d=x.text==="|"||x.text==="||"?{type:"bar",double:x.text==="||",lhs:d,group:v}:{type:"binary",op:x.text,left:d,right:v}}return d}let b,l,s=n[0];if(a&&s.kind==="name"&&s.text==="cbind"&&f(n[1],"(")){let o=n[2],d=n[4],x=h=>h.kind==="name"&&h.text!=="."&&!/^\.[0-9]/.test(h.text);if(!(x(o)&&f(n[3],",")&&x(d)&&f(n[5],")")&&f(n[6],"~")))throw y("the response cbind() must have two column names: cbind(successes, failures)");l=[o.text,d.text],b=l[0],e=6}else if(!f(r(),"~")){let o=c();if(o.kind!=="name"||o.text==="."||!f(r(),"~"))throw y("the response must be a variable name followed by '~'");b=o.text}c();let p=g(0);if(r().kind!=="end")throw y("unexpected input after the formula");return l===void 0?{response:b,rhs:p}:{response:b,responseColumns:l,rhs:p}}function V(t){let u=[],i=e=>{if(e.type==="Error"){u.push(e.arg);return}if(e.type==="paren"){let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}if(e.type==="binary"&&e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.type==="binary"&&e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e},a=i(t),n=e=>{if(e.type==="Error")throw y("Error() must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren")&&n(e.arg)};return a!==void 0&&n(a),u.forEach(n),{treatment:a,errors:u}}function Y(t){let u=[],i=e=>{switch(e.type){case"bar":u.push(e);return;case"paren":{let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}case"binary":if(e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e;default:return e}},a=i(t),n=e=>{if(e.type==="bar")throw y("a random-effects term (lhs | group) must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren"||e.type==="Error")&&n(e.arg)};a!==void 0&&n(a);for(let e of u)n(e.lhs),n(e.group);return{fixed:a,bars:u}}var M=new Set(["+","-","*","%in%"]);function w(t){switch(t.type){case"var":return t.name;case"dot":return".";case"num":return A(t.value);case"binary":{let u=w(t.left),i=w(t.right);return M.has(t.op)?`${u} ${t.op} ${i}`:`${u}${t.op}${i}`}case"unary":return`${t.op}${w(t.arg)}`;case"paren":return`(${w(t.arg)})`;case"Error":return`Error(${w(t.arg)})`;case"bar":return`${w(t.lhs)} ${t.double?"||":"|"} ${w(t.group)}`}}function k(t,u,i){if(t!==void 0)switch(t.type){case"var":i.includes(t.name)||i.push(t.name);return;case"dot":for(let a of u)i.includes(a)||i.push(a);return;case"num":return;case"binary":k(t.left,u,i),t.op!=="^"&&k(t.right,u,i);return;case"unary":case"paren":case"Error":k(t.arg,u,i);return;case"bar":k(t.lhs,u,i),k(t.group,u,i)}}function j(t,u){let i=[];return k(t,u,i),i}var N=t=>t.join(",");function E(t){let u=new Set;return t.filter(i=>{let a=N(i);return u.has(a)?!1:(u.add(a),!0)})}var $=(t,u)=>[...new Set([...t,...u])].sort((i,a)=>i-a);function B(t,u,i){let a=!0,n=(r,c)=>{switch(r.type){case"var":return[[u(r.name)]];case"dot":return i.map(f=>[u(f)]);case"num":if(r.value===1)a=!c;else if(r.value===0)a=c;else throw y(`a number (${r.text}) is not a term`);return[];case"paren":return n(r.arg,c);case"Error":throw y("Error() must be a term of the right-hand side");case"bar":throw y("a random-effects term (lhs | group) must be a term of the right-hand side");case"unary":return r.op==="+"?n(r.arg,c):(n(r.arg,!c),[]);case"binary":{if(r.op==="^"){let l=n(r.left,c),s=r.right;for(;s.type==="paren";)s=s.arg;let p=s.type==="num"?Math.trunc(s.value):NaN;if(!(p>=2&&p<=2147483647))throw new Error("invalid power in formula");let o=l;for(let d=1;d<p;d++){let x=[];for(let S of l)for(let O of o)x.push($(S,O));let h=E(x),v=h.length===o.length&&h.every((S,O)=>N(S)===N(o[O]));if(o=h,v)break}return o}if(r.op==="-"){let l=n(r.left,c),s=new Set(n(r.right,!c).map(N));return l.filter(p=>!s.has(N(p)))}let f=n(r.left,c),m=n(r.right,c);if(f.length===0&&r.op!=="+")return[];let g=()=>{let l=[];for(let s of f)for(let p of m)l.push($(s,p));return l},b=l=>l.reduce((s,p)=>$(s,p),[]);switch(r.op){case"+":return E([...f,...m]);case":":return E(g());case"*":return E([...f,...m,...g()]);case"/":{let l=b(f);return E([...f,...m.map(s=>$(s,l))])}case"%in%":{let l=b(m);return E(f.map(s=>$(s,l)))}}}}throw y("unsupported expression")};return{terms:t===void 0?[]:n(t,!1),intercept:a}}function z(t,u,i=t.rhs){let{response:a,responseColumns:n}=t,e=u.filter(s=>s!==a&&!(n?.includes(s)??!1)),r=a===void 0?[]:[a];n!==void 0&&n[1]!==a&&r.push(n[1]),k(t.rhs,e,r);let f=B(i,s=>r.indexOf(s),e),m=f.terms.map((s,p)=>[s,p]).sort((s,p)=>s[0].length-p[0].length||s[1]-p[1]).map(([s])=>s),g=[],b=a===void 0?-1:m.findIndex(s=>s.length===1&&s[0]===0);b>=0&&(g.push("the response appeared on the right-hand side and was dropped"),g.push(`problem with term ${b+1} in model.matrix: no columns are assigned`));let l=r.map(()=>m.map(()=>0));return m.forEach((s,p)=>{for(let o of s){let d=s.filter(h=>h!==o),x=d.length===0||m.slice(0,p).some(h=>d.every(v=>h.includes(v)));l[o][p]=x?1:2}}),{variables:r,response:a===void 0?-1:0,terms:m,termLabels:m.map(s=>s.map(p=>r[p]).join(":")),order:m.map(s=>s.length),intercept:f.intercept,factors:l,responseTerm:b,warnings:g}}export{I as a,V as b,Y as c,w as d,j as e,B as f,z as g};
1
+ /*! rStats.js 1.3.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{b as A}from"./chunk-UMDXXT3M.js";var y=t=>new SyntaxError(`invalid formula: ${t}`),L=/^(?:[\p{L}\p{Nl}.]|(?![0-9])\p{Nd})[\p{L}\p{Nl}\p{Nd}\p{M}._]*/u;function R(t,u,i=!1){let a=[],n=0;for(;n<t.length;){let e=t[n];if(/\s/.test(e)){n++;continue}if(/[0-9]/.test(e)||e==="."&&/[0-9]/.test(t[n+1]??"")){let c=/^(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(t.slice(n));a.push({kind:"num",text:c[0]}),n+=c[0].length;continue}let r=L.exec(t.slice(n));if(r!==null){a.push({kind:"name",text:r[0]}),n+=r[0].length;continue}if(t.startsWith("%in%",n)){a.push({kind:"op",text:"%in%"}),n+=4;continue}if(u&&e==="|"){let c=t[n+1]==="|"?"||":"|";a.push({kind:"op",text:c}),n+=c.length;continue}if("~+-*/:^()".includes(e)||i&&e===","){a.push({kind:"op",text:e}),n++;continue}throw y(`unexpected '${e}'`)}return a.push({kind:"end"}),a}var T={"|":.5,"||":.5,"+":1,"-":1,"*":2,"/":2,"%in%":3,":":4,"^":6},C=5;function I(t,u=!1,i=!1,a=!1){if(typeof t!="string")throw new TypeError("the formula must be a string");let n=R(t,i,a),e=0,r=()=>n[e],c=()=>n[e++],f=(o,d)=>o.kind==="op"&&o.text===d;function m(){let o=c();if(o.kind==="name"){if(f(r(),"(")){if(o.text!=="Error"||!u)throw y(`function calls are not supported (${o.text})`);c();let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"Error",arg:d}}if(o.text===".")return{type:"dot"};if(/^\.[0-9]/.test(o.text))throw y(`unexpected '${o.text}'`);return{type:"var",name:o.text}}if(o.kind==="num")return{type:"num",value:Number(o.text),text:o.text};if(o.kind==="op"&&o.text==="("){let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"paren",arg:d}}if(o.kind==="op"&&(o.text==="-"||o.text==="+"))return{type:"unary",op:o.text,arg:g(C)};throw y(o.kind==="end"?"unexpected end of input":`unexpected '${o.kind==="op"?o.text:""}'`)}function g(o){let d=m();for(;;){let x=r();if(x.kind!=="op")break;let h=T[x.text];if(h===void 0||h<=o)break;c();let v=g(x.text==="^"?h-1:h);d=x.text==="|"||x.text==="||"?{type:"bar",double:x.text==="||",lhs:d,group:v}:{type:"binary",op:x.text,left:d,right:v}}return d}let b,l,s=n[0];if(a&&s.kind==="name"&&s.text==="cbind"&&f(n[1],"(")){let o=n[2],d=n[4],x=h=>h.kind==="name"&&h.text!=="."&&!/^\.[0-9]/.test(h.text);if(!(x(o)&&f(n[3],",")&&x(d)&&f(n[5],")")&&f(n[6],"~")))throw y("the response cbind() must have two column names: cbind(successes, failures)");l=[o.text,d.text],b=l[0],e=6}else if(!f(r(),"~")){let o=c();if(o.kind!=="name"||o.text==="."||!f(r(),"~"))throw y("the response must be a variable name followed by '~'");b=o.text}c();let p=g(0);if(r().kind!=="end")throw y("unexpected input after the formula");return l===void 0?{response:b,rhs:p}:{response:b,responseColumns:l,rhs:p}}function V(t){let u=[],i=e=>{if(e.type==="Error"){u.push(e.arg);return}if(e.type==="paren"){let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}if(e.type==="binary"&&e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.type==="binary"&&e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e},a=i(t),n=e=>{if(e.type==="Error")throw y("Error() must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren")&&n(e.arg)};return a!==void 0&&n(a),u.forEach(n),{treatment:a,errors:u}}function Y(t){let u=[],i=e=>{switch(e.type){case"bar":u.push(e);return;case"paren":{let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}case"binary":if(e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e;default:return e}},a=i(t),n=e=>{if(e.type==="bar")throw y("a random-effects term (lhs | group) must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren"||e.type==="Error")&&n(e.arg)};a!==void 0&&n(a);for(let e of u)n(e.lhs),n(e.group);return{fixed:a,bars:u}}var M=new Set(["+","-","*","%in%"]);function w(t){switch(t.type){case"var":return t.name;case"dot":return".";case"num":return A(t.value);case"binary":{let u=w(t.left),i=w(t.right);return M.has(t.op)?`${u} ${t.op} ${i}`:`${u}${t.op}${i}`}case"unary":return`${t.op}${w(t.arg)}`;case"paren":return`(${w(t.arg)})`;case"Error":return`Error(${w(t.arg)})`;case"bar":return`${w(t.lhs)} ${t.double?"||":"|"} ${w(t.group)}`}}function k(t,u,i){if(t!==void 0)switch(t.type){case"var":i.includes(t.name)||i.push(t.name);return;case"dot":for(let a of u)i.includes(a)||i.push(a);return;case"num":return;case"binary":k(t.left,u,i),t.op!=="^"&&k(t.right,u,i);return;case"unary":case"paren":case"Error":k(t.arg,u,i);return;case"bar":k(t.lhs,u,i),k(t.group,u,i)}}function j(t,u){let i=[];return k(t,u,i),i}var N=t=>t.join(",");function E(t){let u=new Set;return t.filter(i=>{let a=N(i);return u.has(a)?!1:(u.add(a),!0)})}var $=(t,u)=>[...new Set([...t,...u])].sort((i,a)=>i-a);function B(t,u,i){let a=!0,n=(r,c)=>{switch(r.type){case"var":return[[u(r.name)]];case"dot":return i.map(f=>[u(f)]);case"num":if(r.value===1)a=!c;else if(r.value===0)a=c;else throw y(`a number (${r.text}) is not a term`);return[];case"paren":return n(r.arg,c);case"Error":throw y("Error() must be a term of the right-hand side");case"bar":throw y("a random-effects term (lhs | group) must be a term of the right-hand side");case"unary":return r.op==="+"?n(r.arg,c):(n(r.arg,!c),[]);case"binary":{if(r.op==="^"){let l=n(r.left,c),s=r.right;for(;s.type==="paren";)s=s.arg;let p=s.type==="num"?Math.trunc(s.value):NaN;if(!(p>=2&&p<=2147483647))throw new Error("invalid power in formula");let o=l;for(let d=1;d<p;d++){let x=[];for(let S of l)for(let O of o)x.push($(S,O));let h=E(x),v=h.length===o.length&&h.every((S,O)=>N(S)===N(o[O]));if(o=h,v)break}return o}if(r.op==="-"){let l=n(r.left,c),s=new Set(n(r.right,!c).map(N));return l.filter(p=>!s.has(N(p)))}let f=n(r.left,c),m=n(r.right,c);if(f.length===0&&r.op!=="+")return[];let g=()=>{let l=[];for(let s of f)for(let p of m)l.push($(s,p));return l},b=l=>l.reduce((s,p)=>$(s,p),[]);switch(r.op){case"+":return E([...f,...m]);case":":return E(g());case"*":return E([...f,...m,...g()]);case"/":{let l=b(f);return E([...f,...m.map(s=>$(s,l))])}case"%in%":{let l=b(m);return E(f.map(s=>$(s,l)))}}}}throw y("unsupported expression")};return{terms:t===void 0?[]:n(t,!1),intercept:a}}function z(t,u,i=t.rhs){let{response:a,responseColumns:n}=t,e=u.filter(s=>s!==a&&!(n?.includes(s)??!1)),r=a===void 0?[]:[a];n!==void 0&&n[1]!==a&&r.push(n[1]),k(t.rhs,e,r);let f=B(i,s=>r.indexOf(s),e),m=f.terms.map((s,p)=>[s,p]).sort((s,p)=>s[0].length-p[0].length||s[1]-p[1]).map(([s])=>s),g=[],b=a===void 0?-1:m.findIndex(s=>s.length===1&&s[0]===0);b>=0&&(g.push("the response appeared on the right-hand side and was dropped"),g.push(`problem with term ${b+1} in model.matrix: no columns are assigned`));let l=r.map(()=>m.map(()=>0));return m.forEach((s,p)=>{for(let o of s){let d=s.filter(h=>h!==o),x=d.length===0||m.slice(0,p).some(h=>d.every(v=>h.includes(v)));l[o][p]=x?1:2}}),{variables:r,response:a===void 0?-1:0,terms:m,termLabels:m.map(s=>s.map(p=>r[p]).join(":")),order:m.map(s=>s.length),intercept:f.intercept,factors:l,responseTerm:b,warnings:g}}export{I as a,V as b,Y as c,w as d,j as e,B as f,z as g};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.1.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{e as g}from"./chunk-EJYCDE4Z.js";function b(o,f){let r=o[Symbol.iterator](),s=f[Symbol.iterator]();for(;;){let i=r.next(),t=s.next();if(i.done)return t.done?0:-1;if(t.done)return 1;let l=i.value.codePointAt(0)-t.value.codePointAt(0);if(l!==0)return l}}function y(o,f,r){if(f instanceof Float64Array&&r===void 0){let e=Array.from(f);return{v:{kind:"numeric",values:e},missing:e.map(n=>Number.isNaN(n))}}let s=Array.from(f),i=new Set(s.filter(e=>e!==null).map(e=>typeof e));if(i.size>1)throw new TypeError(`column '${o}' mixes ${[...i].join(" and ")} values`);let t=[...i][0]??"number";if(t!=="number"&&t!=="string"&&t!=="boolean")throw new TypeError(`column '${o}' has values of an unsupported type`);if(t==="number"&&r===void 0){let e=s.map(n=>n===null?NaN:n);return{v:{kind:"numeric",values:e},missing:e.map(n=>Number.isNaN(n))}}let l=e=>e===null||typeof e=="number"&&Number.isNaN(e)?null:typeof e=="boolean"?e?"TRUE":"FALSE":g(e),c=s.map(l),u;if(r!==void 0){u=Array.from(r,String);let e=u.findIndex((n,p)=>u.indexOf(n)!==p);if(e>=0)throw new RangeError(`factor level [${e+1}] is duplicated`)}else t==="boolean"?u=["FALSE","TRUE"]:u=[...new Set(c.filter(e=>e!==null))].sort(b);let a=new Map(u.map((e,n)=>[e,n])),m=c.map(e=>e===null?-1:a.get(e)??-1),d=r!==void 0?"given":t==="boolean"?"logical":"values";return{v:{kind:"factor",levels:u,codes:m},missing:m.map(e=>e<0),source:d}}function h(o,f){let r=o.map(()=>!1);for(let t of f)r[t]=!0;let s=new Map;return{levels:o.filter((t,l)=>(r[l]&&s.set(l,s.size),r[l])),codes:f.map(t=>s.get(t))}}function E(o){return h(o.levels,o.codes)}function N(o,f,r={}){if(typeof o!="object"||o===null)throw new TypeError("data must be an object of columns");let s=f.map(e=>{let n=Object.prototype.hasOwnProperty.call(o,e)?o[e]:void 0;if(n===void 0)throw new RangeError(`object '${e}' not found`);if(!Array.isArray(n)&&!(n instanceof Float64Array))throw new TypeError(`column '${e}' must be an array`);return n}),i;if(typeof r.weights=="string"){let e=Object.prototype.hasOwnProperty.call(o,r.weights)?o[r.weights]:void 0;if(e===void 0)throw new RangeError(`object '${r.weights}' not found`);i=e}else r.weights!==void 0&&(i=Array.from(r.weights));let t=s.length>0?s[0].length:i?.length??Object.values(o)[0]?.length??0;if(f.forEach((e,n)=>{if(s[n].length!==t)throw new RangeError(`variable lengths differ (found for '${e}')`)}),i!==void 0&&i.length!==t)throw new RangeError("variable lengths differ (found for '(weights)')");let{levels:l}=r,c=f.map((e,n)=>y(e,s[n],l!==void 0&&Object.hasOwn(l,e)?l[e]:void 0)),u;i!==void 0&&(u=Array.from(i,e=>{if(e===null)return NaN;if(typeof e!="number")throw new TypeError("the weights must be numeric");return e}));let a=[];for(let e=0;e<t;e++)c.some(n=>n.missing[e])||u!==void 0&&Number.isNaN(u[e])||a.push(e);let m=c.map(({v:e,source:n})=>{if(e.kind==="numeric")return{kind:"numeric",values:a.map(w=>e.values[w])};let p=a.map(w=>e.codes[w]);return n==="values"||n==="given"&&r.dropUnusedLevels?{kind:"factor",...h(e.levels,p)}:{kind:"factor",levels:e.levels,codes:p}}),d={rows:a,variables:m};if(u!==void 0&&(d.weights=a.map(e=>u[e]),d.weights.some(e=>e<0)))throw new RangeError("missing or negative weights not allowed");return d}export{b as a,E as b,N as c};
1
+ /*! rStats.js 1.3.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{e as g}from"./chunk-UMDXXT3M.js";function b(o,f){let r=o[Symbol.iterator](),s=f[Symbol.iterator]();for(;;){let i=r.next(),t=s.next();if(i.done)return t.done?0:-1;if(t.done)return 1;let l=i.value.codePointAt(0)-t.value.codePointAt(0);if(l!==0)return l}}function y(o,f,r){if(f instanceof Float64Array&&r===void 0){let e=Array.from(f);return{v:{kind:"numeric",values:e},missing:e.map(n=>Number.isNaN(n))}}let s=Array.from(f),i=new Set(s.filter(e=>e!==null).map(e=>typeof e));if(i.size>1)throw new TypeError(`column '${o}' mixes ${[...i].join(" and ")} values`);let t=[...i][0]??"number";if(t!=="number"&&t!=="string"&&t!=="boolean")throw new TypeError(`column '${o}' has values of an unsupported type`);if(t==="number"&&r===void 0){let e=s.map(n=>n===null?NaN:n);return{v:{kind:"numeric",values:e},missing:e.map(n=>Number.isNaN(n))}}let l=e=>e===null||typeof e=="number"&&Number.isNaN(e)?null:typeof e=="boolean"?e?"TRUE":"FALSE":g(e),c=s.map(l),u;if(r!==void 0){u=Array.from(r,String);let e=u.findIndex((n,p)=>u.indexOf(n)!==p);if(e>=0)throw new RangeError(`factor level [${e+1}] is duplicated`)}else t==="boolean"?u=["FALSE","TRUE"]:u=[...new Set(c.filter(e=>e!==null))].sort(b);let a=new Map(u.map((e,n)=>[e,n])),m=c.map(e=>e===null?-1:a.get(e)??-1),d=r!==void 0?"given":t==="boolean"?"logical":"values";return{v:{kind:"factor",levels:u,codes:m},missing:m.map(e=>e<0),source:d}}function h(o,f){let r=o.map(()=>!1);for(let t of f)r[t]=!0;let s=new Map;return{levels:o.filter((t,l)=>(r[l]&&s.set(l,s.size),r[l])),codes:f.map(t=>s.get(t))}}function E(o){return h(o.levels,o.codes)}function N(o,f,r={}){if(typeof o!="object"||o===null)throw new TypeError("data must be an object of columns");let s=f.map(e=>{let n=Object.prototype.hasOwnProperty.call(o,e)?o[e]:void 0;if(n===void 0)throw new RangeError(`object '${e}' not found`);if(!Array.isArray(n)&&!(n instanceof Float64Array))throw new TypeError(`column '${e}' must be an array`);return n}),i;if(typeof r.weights=="string"){let e=Object.prototype.hasOwnProperty.call(o,r.weights)?o[r.weights]:void 0;if(e===void 0)throw new RangeError(`object '${r.weights}' not found`);i=e}else r.weights!==void 0&&(i=Array.from(r.weights));let t=s.length>0?s[0].length:i?.length??Object.values(o)[0]?.length??0;if(f.forEach((e,n)=>{if(s[n].length!==t)throw new RangeError(`variable lengths differ (found for '${e}')`)}),i!==void 0&&i.length!==t)throw new RangeError("variable lengths differ (found for '(weights)')");let{levels:l}=r,c=f.map((e,n)=>y(e,s[n],l!==void 0&&Object.hasOwn(l,e)?l[e]:void 0)),u;i!==void 0&&(u=Array.from(i,e=>{if(e===null)return NaN;if(typeof e!="number")throw new TypeError("the weights must be numeric");return e}));let a=[];for(let e=0;e<t;e++)c.some(n=>n.missing[e])||u!==void 0&&Number.isNaN(u[e])||a.push(e);let m=c.map(({v:e,source:n})=>{if(e.kind==="numeric")return{kind:"numeric",values:a.map(w=>e.values[w])};let p=a.map(w=>e.codes[w]);return n==="values"||n==="given"&&r.dropUnusedLevels?{kind:"factor",...h(e.levels,p)}:{kind:"factor",levels:e.levels,codes:p}}),d={rows:a,variables:m};if(u!==void 0&&(d.weights=a.map(e=>u[e]),d.weights.some(e=>e<0)))throw new RangeError("missing or negative weights not allowed");return d}export{b as a,E as b,N as c};