@numero-uno-jpn/rstats 1.10.0 → 1.12.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 (108) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.ja.md +8 -6
  3. package/README.md +8 -6
  4. package/dist/causal/balance.d.ts +106 -0
  5. package/dist/causal/balance.js +216 -0
  6. package/dist/causal/match.d.ts +86 -0
  7. package/dist/causal/match.js +155 -0
  8. package/dist/causal/scale.d.ts +8 -0
  9. package/dist/causal/scale.js +26 -0
  10. package/dist/causal.js +2 -0
  11. package/dist/chunks/chunk-2P42OXYW.js +2 -0
  12. package/dist/chunks/{chunk-GYLFMAD6.js → chunk-3QOW56EJ.js} +2 -2
  13. package/dist/chunks/chunk-3QSYPBUM.js +2 -0
  14. package/dist/chunks/chunk-4B7NEJCE.js +2 -0
  15. package/dist/chunks/{chunk-PJ73WRSA.js → chunk-4GRV66HW.js} +2 -2
  16. package/dist/chunks/chunk-4U65I4J2.js +2 -0
  17. package/dist/chunks/chunk-52KGBGFL.js +2 -0
  18. package/dist/chunks/{chunk-Y7SXBQZY.js → chunk-5AR4V7MW.js} +2 -2
  19. package/dist/chunks/chunk-7FXBOYIH.js +2 -0
  20. package/dist/chunks/{chunk-ZUHBIFAJ.js → chunk-7K2LMKZR.js} +2 -2
  21. package/dist/chunks/chunk-7UI4PW32.js +2 -0
  22. package/dist/chunks/{chunk-IFFGJN5L.js → chunk-CHKBDZC4.js} +2 -2
  23. package/dist/chunks/chunk-CKBUE4FV.js +2 -0
  24. package/dist/chunks/chunk-CMTCPLIA.js +2 -0
  25. package/dist/chunks/chunk-DWVTVOQS.js +2 -0
  26. package/dist/chunks/chunk-FFMMKXMK.js +2 -0
  27. package/dist/chunks/chunk-HF3QOIZX.js +2 -0
  28. package/dist/chunks/chunk-JG26HC2H.js +2 -0
  29. package/dist/chunks/chunk-L54WIMTZ.js +3 -0
  30. package/dist/chunks/{chunk-ISNGTKVZ.js → chunk-MAFZ5FGL.js} +2 -2
  31. package/dist/chunks/{chunk-F3WMBL5R.js → chunk-MJ7IY7AF.js} +2 -2
  32. package/dist/chunks/chunk-MUYGPZ37.js +3 -0
  33. package/dist/chunks/chunk-NAACMR7H.js +2 -0
  34. package/dist/chunks/chunk-NGDBJR3K.js +2 -0
  35. package/dist/chunks/chunk-NQT7ZWL6.js +2 -0
  36. package/dist/chunks/{chunk-6U2ICRN3.js → chunk-O6OMXX5U.js} +1 -1
  37. package/dist/chunks/chunk-PYFASERO.js +2 -0
  38. package/dist/chunks/chunk-QT32BMYA.js +2 -0
  39. package/dist/chunks/{chunk-6BDTLUNM.js → chunk-SKQHW2GD.js} +2 -2
  40. package/dist/chunks/{chunk-EDHAQHB7.js → chunk-SLMS3FQD.js} +1 -1
  41. package/dist/chunks/{chunk-6Y7OKIIM.js → chunk-SZR5HAMB.js} +2 -2
  42. package/dist/chunks/chunk-T5TE5KCP.js +2 -0
  43. package/dist/chunks/chunk-ULQXNAI6.js +2 -0
  44. package/dist/chunks/chunk-UPFMYDF7.js +2 -0
  45. package/dist/chunks/{chunk-DC2FP6ZH.js → chunk-WACTNIKS.js} +2 -2
  46. package/dist/chunks/{chunk-F5K2UXKW.js → chunk-WSDLT4AR.js} +1 -1
  47. package/dist/chunks/chunk-WUNTM7PJ.js +2 -0
  48. package/dist/chunks/chunk-XQSYV3IZ.js +2 -0
  49. package/dist/chunks/chunk-YKCZF4ES.js +2 -0
  50. package/dist/chunks/{chunk-NNJGXB5K.js → chunk-ZHAT6244.js} +2 -2
  51. package/dist/chunks/{chunk-OQFZKQVT.js → chunk-ZK7FW5UX.js} +2 -2
  52. package/dist/descriptive.js +2 -2
  53. package/dist/distributions.js +2 -2
  54. package/dist/entries/causal.d.ts +2 -0
  55. package/dist/entries/causal.js +3 -0
  56. package/dist/entries/multivariate.d.ts +4 -0
  57. package/dist/entries/multivariate.js +4 -0
  58. package/dist/entries/tests.d.ts +1 -0
  59. package/dist/entries/tests.js +1 -0
  60. package/dist/entries/timeseries.d.ts +1 -0
  61. package/dist/entries/timeseries.js +2 -0
  62. package/dist/linalg.js +2 -2
  63. package/dist/mixed.js +2 -2
  64. package/dist/models/clogit.d.ts +80 -0
  65. package/dist/models/clogit.js +211 -0
  66. package/dist/models/coxph.d.ts +9 -0
  67. package/dist/models/coxph.js +3 -3
  68. package/dist/multivariate/ca.d.ts +120 -0
  69. package/dist/multivariate/ca.js +230 -0
  70. package/dist/multivariate/isoMDS.d.ts +55 -0
  71. package/dist/multivariate/isoMDS.js +409 -0
  72. package/dist/multivariate/mjca.d.ts +125 -0
  73. package/dist/multivariate/mjca.js +243 -0
  74. package/dist/multivariate/sammon.d.ts +66 -0
  75. package/dist/multivariate/sammon.js +231 -0
  76. package/dist/multivariate.js +2 -2
  77. package/dist/numerics.js +2 -2
  78. package/dist/regression.js +2 -2
  79. package/dist/rstats.js +18 -18
  80. package/dist/special.js +2 -2
  81. package/dist/tests.js +15 -15
  82. package/dist/timeseries/acf.d.ts +80 -0
  83. package/dist/timeseries/acf.js +314 -0
  84. package/dist/timeseries.js +2 -0
  85. package/llms.txt +51 -2
  86. package/package.json +11 -1
  87. package/dist/chunks/chunk-3QUOB47N.js +0 -2
  88. package/dist/chunks/chunk-5PVS6TF2.js +0 -2
  89. package/dist/chunks/chunk-AQ7H4RJH.js +0 -2
  90. package/dist/chunks/chunk-CN5D6ITZ.js +0 -3
  91. package/dist/chunks/chunk-F232C4SB.js +0 -3
  92. package/dist/chunks/chunk-JPQEOHZG.js +0 -2
  93. package/dist/chunks/chunk-JRMISESC.js +0 -2
  94. package/dist/chunks/chunk-K25FNCFH.js +0 -2
  95. package/dist/chunks/chunk-KGDCQ2RV.js +0 -2
  96. package/dist/chunks/chunk-LQWAHXHZ.js +0 -2
  97. package/dist/chunks/chunk-MBQJWNPX.js +0 -2
  98. package/dist/chunks/chunk-MULNGWZY.js +0 -2
  99. package/dist/chunks/chunk-MVIBJA2I.js +0 -2
  100. package/dist/chunks/chunk-NAUAW5TO.js +0 -2
  101. package/dist/chunks/chunk-NMVFSSEZ.js +0 -2
  102. package/dist/chunks/chunk-OXYMJNVJ.js +0 -2
  103. package/dist/chunks/chunk-R5BXUEH3.js +0 -2
  104. package/dist/chunks/chunk-RPEFV4FR.js +0 -2
  105. package/dist/chunks/chunk-T3XFVWOW.js +0 -2
  106. package/dist/chunks/chunk-Y5M7NEJ5.js +0 -2
  107. package/dist/chunks/chunk-YCBQQHCB.js +0 -2
  108. package/dist/chunks/chunk-YGKM6PIJ.js +0 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,23 @@ 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.12.0 - 2026-11-24
11
+
12
+ ### Added
13
+
14
+ - **Causal inference** in the separate `/causal` area: propensity score matching (`match`, after `Matching::Match` with `ties = FALSE` and `replace = FALSE`: ATT, ATE and ATC, 1:M, caliper), matching weights (`matchWeights`), covariate balance before and after (`balTab`, after `cobalt::bal.tab`) and tableone's standardized mean difference (`tableOneSmd`).
15
+ - **Conditional logistic regression** (`clogit`, after `survival::clogit`): the exact conditional likelihood and the approximate (Breslow) one.
16
+ - Ties among three or more matching candidates are broken by rStats.js's own rule; without ties, and with two tied candidates, the pairs and the random numbers are R's ([the differences](docs/differences-from-r.md#propensity-score-matching-and-conditional-logistic-regression-1120)).
17
+
18
+ ## 1.11.0 - 2026-11-24
19
+
20
+ ### Added
21
+
22
+ - **Time series** in the separate `/timeseries` area: autocorrelation, partial autocorrelation and cross-correlation (`acf`, `pacf`, `ccf`).
23
+ - **Multivariate analysis** in `/multivariate`: correspondence analysis (`ca`, `caSummary`, `caCoord`), multiple correspondence analysis (`mjca`) and non-metric multidimensional scaling (`sammon`, `isoMDS`).
24
+ - Numerical safeguards and independent checks for extreme scales, large offsets, long series, close points and large multivariate inputs.
25
+ - `isoMDS` follows R's BFGS path from the identity in the original coordinate scale; PACF uses the ordinary double-precision Durbin–Levinson recursion.
26
+
10
27
  ## 1.10.0 - 2026-11-23
11
28
 
12
29
  ### Added
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.10.0。** R の stats パッケージの数値計算の中心
19
+ 状態: **1.12.0。** R の stats パッケージの数値計算の中心
20
20
  (分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
21
21
  [ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
22
22
 
@@ -218,6 +218,8 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
218
218
  | 特殊関数 | `gamma`, `lgamma`, `beta`, `lbeta`, `choose`, `lchoose`, `factorial`, `lfactorial`, `digamma`, `trigamma`, `psigamma`, `besselI`, `besselK`, `besselJ`, `besselY`。R にはない `erf`, `erfc`, `erfinv`, `erfcinv`, `gammainc`, `perm` と、R の C API (Rmath.h) の `log1pmx`, `lgamma1p`, `log1mexp`, `log1pexp` も |
219
219
  | 分布 (d/p/q) | 正規、t、カイ二乗、F、ベータ、ガンマ、二項、ポアソン、一様、指数、対数正規、ロジスティック、コーシー、ワイブル、幾何、負の二項、超幾何、Wilcoxon の符号付き順位と順位和、スチューデント化された範囲 (`ptukey`, `qtukey`)、非心カイ二乗・t・F・ベータ (`ncp`)。多項分布の確率 (`dmultinom`)。逆ガンマ、Kumaraswamy、Pareto、三角、Laplace (extraDistr) と逆正弦。`distSummary` (平均・分散・標準偏差・中央値・最頻値・歪度・尖度) |
220
220
  | 乱数 | `setSeed` (`set.seed`), `RNGkind` (Mersenne-Twister と L'Ecuyer-CMRG、`sample.kind` の Rejection と Rounding), `getRandomSeed`/`setRandomSeed` (`.Random.seed`), `nextRNGStream`/`nextRNGSubStream` (`parallel`), 26 個の `r*` 関数, `sample`, `sampleInt` (`sample.int`), `r2dtable` |
221
+ | 時系列 | `acf`、`pacf`、`ccf` (`stats::acf`、`stats::pacf`、`stats::ccf`)、`@numero-uno-jpn/rstats/timeseries` |
222
+ | 因果推論 | `match` (傾向スコアのマッチング: `ties = FALSE`・`replace = FALSE` の `Matching::Match`。ATT・ATE・ATC、1:M、キャリパー)、`matchWeights` (`cobalt::get.w`)、`balTab` (マッチング前後の標準化平均差と分散比: `cobalt::bal.tab`)、`tableOneSmd` (`tableone::ExtractSmd`)、`@numero-uno-jpn/rstats/causal` |
221
223
  | 記述統計 | `sum`, `prod`, `mean`, `weightedMean` (`weighted.mean`), `variance` (`var`), `sd`, `median`, `range`, `cumsum`, `cumprod`, `cummax`, `cummin`, `diff`, `quantile`, `IQR`, `fivenum`, `mad`, `rank`, `cov`, `cor`, `tabulate`, `table`, `unique`, `cut`, `findInterval`, `pretty`, `hist`, `ecdf`, `scale`, `skewness`, `kurtosis`, `geometricMean`, `modes`, `meanAD`, `cv` |
222
224
  | 検定 | `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`, `tamhaneT2Test` (Tamhane の T2 と T2')、`pageTest`、`grubbsTest`・`pgrubbs`・`qgrubbs`、`pAdjust` (`p.adjust`) |
223
225
  | 分散分析 | formula で呼ぶ `aov` と `aovSummary` (多元、交互作用、共変量、`Error()` の層), `anova` (`anova.lm`。逐次の表とモデルの比較), `Anova` (car の Type II と III), `aovEz` (afex。反復測定と混合計画、Greenhouse-Geisser と Huynh-Feldt の補正、一般化 η² と偏 η²), `mauchlyTest` (`mauchly.test`) |
@@ -226,13 +228,13 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
226
228
  | メタアナリシス | `escalc` (効果量と標本分散)、`rma` (等効果・ランダム効果のメタアナリシスとメタ回帰)、`confintRma`・`predictRma`・`regtest` (metafor) |
227
229
  | 線形モデル | `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) |
228
230
  | 回帰 | `polr`・`polrSummary`・`polrVcov`・`polrPredict`・`polrConfint`・`polrAnova` (MASS: logistic・probit・cloglog・loglog・cauchit のリンクによる順序ロジスティック回帰)、`rlm`・`rlmSummary`・`rlmVcov`・`psiHuber`・`psiHampel`・`psiBisquare` (MASS: M 推定と MM 推定によるロバスト回帰)、`nls`・`nlsSummary`・`nlsVcov`・`nlsPredict`・`nlsConfint`・`nlsAnova` (非線形最小二乗法: 既定・`plinear`・`port` のアルゴリズムと 10 個の自己開始モデル)、`rq`・`rqSummary`・`rqPredict`・`rqPredictInterval`・`rqAnova` (分位点回帰)、`geeglm`・`geeSummary`・`geeVcov`・`geePredict`・`geeAnova`・`geeQIC` (一般化推定方程式)、`glmnet`・`glmnetCoef`・`glmnetPredict`・`cvGlmnet` (Gaussian・binomial・Poisson・multinomial の正則化回帰)。`@numero-uno-jpn/rstats/regression` から import します |
229
- | 多変量解析 | `manova`・`manovaSummary` (逐次 MANOVA: Pillai・Wilks・Hotelling-Lawley・Roy)、`lda`・`ldaPredict` (線形判別分析)、`cancor` (正準相関)、`dist`・`asDist`・`hclust`・`cutree`・`kmeans` (クラスタ分析)、`cmdscale` (古典的多次元尺度法)。`@numero-uno-jpn/rstats/multivariate` から import します |
231
+ | 多変量解析 | `manova`・`manovaSummary` (逐次 MANOVA: Pillai・Wilks・Hotelling-Lawley・Roy)、`lda`・`ldaPredict` (線形判別分析)、`cancor` (正準相関)、`dist`・`asDist`・`hclust`・`cutree`・`kmeans` (クラスタ分析)、`cmdscale` (古典的多次元尺度法)、`ca`・`caSummary`・`caCoord` (対応分析)、`mjca` (多重対応分析)、`sammon`・`isoMDS` (非計量多次元尺度法)。`@numero-uno-jpn/rstats/multivariate` から import します |
230
232
  | 混合モデル | `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`・`confintLmer`・`confintGlmer`・`simulateLmer`・`simulateGlmer`。
231
233
  `@numero-uno-jpn/rstats/mixed` から import する |
232
234
  | ほかの検定 | `leveneTest`、`propTrendTest` (`prop.trend.test`)、`jonckheereTest`、`cochranQTest`、`adTest`、`lillieTest`、`cvmTest`、`sfTest`、`pearsonTest` (car、DescTools、clinfun、nortest)。`tTOST`、`tsumTOST` (TOSTER: 平均の同等性検定と最小効果検定) |
233
235
  | 分割表と比率 | `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) |
234
236
  | 多重比較 | `dscfAllPairsTest` (Steel-Dwass)、`kwAllPairsDunnTest`、`kwManyOneDunnTest`、`manyOneUTest` (Steel の多対一の順位検定)、`dunnettTest`、`gamesHowellTest`、`tukeyTest` (PMCMRplus)、`dunnTest` (dunn.test)、`glhtDunnett` (multcomp) |
235
- | 生存時間解析 | `survdiff` (log-rank と G-rho 族)、`survfit` (Kaplan-Meier と Nelson-Aalen・Fleming-Harrington の累積ハザード、重み、ロバスト標準誤差、信頼区間、中央値、制限平均、計数過程データ)、`rmst2` (非調整・共変量調整の制限平均生存時間と制限平均損失時間)、`coxph` (Cox 回帰。Efron と Breslow のタイ、ケース重み、層、Wald・尤度比・スコア検定、計数過程データ、ロバスト分散と `cluster`)、`coxZph` (比例ハザード性の検定)、`cuminc`・`timepoints` (累積発生率と Gray の検定)、`crr`・`predictCrr` (Fine-Gray 回帰と予測)、`survreg`・`survregPredict`・`survregResiduals` (パラメトリックな加速故障時間回帰) |
237
+ | 生存時間解析 | `survdiff` (log-rank と G-rho 族)、`survfit` (Kaplan-Meier と Nelson-Aalen・Fleming-Harrington の累積ハザード、重み、ロバスト標準誤差、信頼区間、中央値、制限平均、計数過程データ)、`rmst2` (非調整・共変量調整の制限平均生存時間と制限平均損失時間)、`coxph` (Cox 回帰。Efron と Breslow のタイ、ケース重み、層、Wald・尤度比・スコア検定、計数過程データ、ロバスト分散と `cluster`)、`clogit` (マッチした組の条件付きロジスティック回帰: 正確な尤度と近似の尤度)、`coxZph` (比例ハザード性の検定)、`cuminc`・`timepoints` (累積発生率と Gray の検定)、`crr`・`predictCrr` (Fine-Gray 回帰と予測)、`survreg`・`survregPredict`・`survregResiduals` (パラメトリックな加速故障時間回帰) |
236
238
  | 診断の精度と測定法の比較 | `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 回帰) |
237
239
  | 一致度と信頼性 | `kappa2`、`kappamFleiss`、`icc` (irr)、`ICC` (psych: Shrout と Fleiss の 6 つの形式)、`cronbachAlpha`、`partialR` (psych)、`polychor`、`polyserial` (polycor)、`pbvnorm`、`factanal`、`omega` (McDonald の ω。psych) |
238
240
  | データの扱い | `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)` など) |
@@ -315,7 +317,7 @@ minify 済みの ES モジュール、gzip で 322 KB) を jsDelivr から読み
315
317
 
316
318
  ```html
317
319
  <script type="module">
318
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.10.0/dist/rstats.js";
320
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.12.0/dist/rstats.js";
319
321
  console.log(pnorm(1.96)); // ≈ 0.9750021049
320
322
  </script>
321
323
  ```
@@ -329,13 +331,13 @@ minify 済みの ES モジュール、gzip で 322 KB) を jsDelivr から読み
329
331
 
330
332
  一部の分野だけを使うページでは、代わりに分野ごとのバンドルを読み込めます。`dist/distributions.js`、
331
333
  `dist/tests.js`、`dist/linalg.js`、`dist/descriptive.js`、`dist/numerics.js`、`dist/special.js`、
332
- `dist/mixed.js`、`dist/regression.js`、`dist/multivariate.js` は上のサブパスと同じ関数を export し、共通のコードを `dist/chunks/` で共有します。そのため、
334
+ `dist/mixed.js`、`dist/regression.js`、`dist/multivariate.js`、`dist/timeseries.js`、`dist/causal.js` は上のサブパスと同じ関数を export し、共通のコードを `dist/chunks/` で共有します。そのため、
333
335
  2 つの分野を読み込んでも共通部分は 1 回しか読み込まれません。chunk を含めた 1 分野の転送量は、gzip で
334
336
  39 KB (`special`) から 288 KB (`tests`) です。
335
337
 
336
338
  1 つのページでは、`dist/rstats.js` か分野ごとのバンドルのどちらか一方だけを使ってください。両者は別々の
337
339
  モジュールの集まりなので、混ぜると共通のコードが 2 回読み込まれ、乱数の状態も 2 つになります (一方の `setSeed`
338
- は他方の乱数に効きません)。`dist/rstats.js` と `dist/mixed.js`・`dist/regression.js`・`dist/multivariate.js` を一緒に読み込む場合も、
340
+ は他方の乱数に効きません)。`dist/rstats.js` と `dist/mixed.js`・`dist/regression.js`・`dist/multivariate.js`・`dist/timeseries.js`・`dist/causal.js` を一緒に読み込む場合も、
339
341
  これらは共通のコードを別に持ち込みます。
340
342
 
341
343
  npm を元にしたほかの CDN も使えます。たとえば `https://esm.sh/@numero-uno-jpn/rstats` です。ビルド結果
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.10.0.** The goal is to cover the numerical core of R's
17
+ Status: **1.12.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
 
@@ -216,6 +216,8 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
216
216
  | Special functions | `gamma`, `lgamma`, `beta`, `lbeta`, `choose`, `lchoose`, `factorial`, `lfactorial`, `digamma`, `trigamma`, `psigamma`, `besselI`, `besselK`, `besselJ`, `besselY`; also `erf`, `erfc`, `erfinv`, `erfcinv`, `gammainc` and `perm`, which R lacks, and `log1pmx`, `lgamma1p`, `log1mexp`, `log1pexp` from R's C API (Rmath.h) |
217
217
  | Distributions (d/p/q) | normal, t, chi-squared, F, beta, gamma, binomial, Poisson, uniform, exponential, log-normal, logistic, Cauchy, Weibull, geometric, negative binomial, hypergeometric, Wilcoxon signed rank and rank sum, studentized range (`ptukey`, `qtukey`), non-central chi-squared, t, F and beta (`ncp`); the multinomial probability (`dmultinom`); inverse gamma, Kumaraswamy, Pareto, triangular, Laplace (extraDistr) and arcsine; `distSummary` (mean, variance, sd, median, mode, skewness, kurtosis) |
218
218
  | Random numbers | `setSeed` (`set.seed`), `RNGkind` (Mersenne-Twister and L'Ecuyer-CMRG, `sample.kind` Rejection and Rounding), `getRandomSeed`/`setRandomSeed` (`.Random.seed`), `nextRNGStream`/`nextRNGSubStream` (`parallel`), 26 `r*` functions, `sample`, `sampleInt` (`sample.int`), `r2dtable` |
219
+ | Time series | `acf`, `pacf`, `ccf` (`stats::acf`, `stats::pacf`, `stats::ccf`) from `@numero-uno-jpn/rstats/timeseries` |
220
+ | Causal inference | `match` (propensity score matching: `Matching::Match` with `ties = FALSE`, `replace = FALSE`; ATT, ATE and ATC, 1:M, caliper), `matchWeights` (`cobalt::get.w`), `balTab` (standardized mean differences and variance ratios before and after: `cobalt::bal.tab`) and `tableOneSmd` (`tableone::ExtractSmd`), from `@numero-uno-jpn/rstats/causal` |
219
221
  | Descriptive statistics | `sum`, `prod`, `mean`, `weightedMean` (`weighted.mean`), `variance` (`var`), `sd`, `median`, `range`, `cumsum`, `cumprod`, `cummax`, `cummin`, `diff`, `quantile`, `IQR`, `fivenum`, `mad`, `rank`, `cov`, `cor`, `tabulate`, `table`, `unique`, `cut`, `findInterval`, `pretty`, `hist`, `ecdf`, `scale`, `skewness`, `kurtosis`, `geometricMean`, `modes`, `meanAD`, `cv` |
220
222
  | 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`, `tamhaneT2Test` (Tamhane's T2/T2'), `pageTest`, `grubbsTest`, `pgrubbs`, `qgrubbs`, `pAdjust` (`p.adjust`) |
221
223
  | 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`) |
@@ -224,13 +226,13 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
224
226
  | Meta-analysis | `escalc` (effect sizes and sampling variances), `rma` (equal- and random-effects meta-analysis and meta-regression), `confintRma`, `predictRma`, `regtest` (metafor) |
225
227
  | 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) |
226
228
  | Regression | `polr`, `polrSummary`, `polrVcov`, `polrPredict`, `polrConfint`, `polrAnova` (MASS: ordinal logistic regression with logistic, probit, cloglog, loglog and cauchit links); `rlm`, `rlmSummary`, `rlmVcov`, `psiHuber`, `psiHampel`, `psiBisquare` (MASS: robust M and MM regression); `nls`, `nlsSummary`, `nlsVcov`, `nlsPredict`, `nlsConfint`, `nlsAnova` (nonlinear least squares: default, `plinear` and `port` algorithms, and 10 self-starting models); `rq`, `rqSummary`, `rqPredict`, `rqPredictInterval`, `rqAnova` (quantile regression); `geeglm`, `geeSummary`, `geeVcov`, `geePredict`, `geeAnova`, `geeQIC` (generalized estimating equations); `glmnet`, `glmnetCoef`, `glmnetPredict`, `cvGlmnet` (penalized Gaussian, binomial, Poisson and multinomial regression), from `@numero-uno-jpn/rstats/regression` |
227
- | Multivariate analysis | `manova`, `manovaSummary` (sequential MANOVA: Pillai, Wilks, Hotelling-Lawley and Roy); `lda`, `ldaPredict` (linear discriminant analysis); `cancor` (canonical correlation); `dist`, `asDist`, `hclust`, `cutree`, `kmeans` (cluster analysis) and `cmdscale` (classical multidimensional scaling), from `@numero-uno-jpn/rstats/multivariate` |
229
+ | Multivariate analysis | `manova`, `manovaSummary` (sequential MANOVA: Pillai, Wilks, Hotelling-Lawley and Roy); `lda`, `ldaPredict` (linear discriminant analysis); `cancor` (canonical correlation); `dist`, `asDist`, `hclust`, `cutree`, `kmeans` (cluster analysis); `cmdscale` (classical multidimensional scaling); `ca`, `caSummary`, `caCoord` (correspondence analysis); `mjca` (multiple correspondence analysis); `sammon` and `isoMDS` (non-metric multidimensional scaling), from `@numero-uno-jpn/rstats/multivariate` |
228
230
  | 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`, `lmerPredict`, `confintLmer`, `confintGlmer`, `simulateLmer` and
229
231
  `simulateGlmer`, from `@numero-uno-jpn/rstats/mixed` |
230
232
  | 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) |
231
233
  | 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) |
232
234
  | Multiple comparisons | `dscfAllPairsTest` (Steel-Dwass), `kwAllPairsDunnTest`, `kwManyOneDunnTest`, `manyOneUTest` (Steel's many-one rank test), `dunnettTest`, `gamesHowellTest`, `tukeyTest` (PMCMRplus), `dunnTest` (dunn.test), `glhtDunnett` (multcomp) |
233
- | Survival analysis | `survdiff` (log-rank and the G-rho family), `survfit` (Kaplan-Meier and Nelson-Aalen/Fleming-Harrington cumulative hazards, weights, robust standard errors, confidence intervals, medians, restricted means and counting-process data), `rmst2` (unadjusted and covariate-adjusted restricted mean survival time and time lost), `coxph` (Cox regression: Efron and Breslow ties, case weights, strata, Wald, likelihood-ratio and score tests, counting-process data, robust variance and `cluster`), `coxZph` (proportional-hazards tests), `cuminc` and `timepoints` (cumulative incidence and Gray's tests), `crr` and `predictCrr` (Fine-Gray regression and predictions), `survreg`, `survregPredict` and `survregResiduals` (parametric accelerated-failure-time regression) |
235
+ | Survival analysis | `survdiff` (log-rank and the G-rho family), `survfit` (Kaplan-Meier and Nelson-Aalen/Fleming-Harrington cumulative hazards, weights, robust standard errors, confidence intervals, medians, restricted means and counting-process data), `rmst2` (unadjusted and covariate-adjusted restricted mean survival time and time lost), `coxph` (Cox regression: Efron and Breslow ties, case weights, strata, Wald, likelihood-ratio and score tests, counting-process data, robust variance and `cluster`), `clogit` (conditional logistic regression for matched sets: exact and approximate likelihoods), `coxZph` (proportional-hazards tests), `cuminc` and `timepoints` (cumulative incidence and Gray's tests), `crr` and `predictCrr` (Fine-Gray regression and predictions), `survreg`, `survregPredict` and `survregResiduals` (parametric accelerated-failure-time regression) |
234
236
  | 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) |
235
237
  | 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) |
236
238
  | 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)`, ...) |
@@ -314,7 +316,7 @@ function except those of `/mixed` and `/regression`, 322 KB gzipped) from jsDeli
314
316
 
315
317
  ```html
316
318
  <script type="module">
317
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.10.0/dist/rstats.js";
319
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.12.0/dist/rstats.js";
318
320
  console.log(pnorm(1.96)); // ≈ 0.9750021049
319
321
  </script>
320
322
  ```
@@ -328,13 +330,13 @@ browser console, assign `window.rs = rs` yourself.
328
330
 
329
331
  A page that needs only some areas can load the per-area bundles instead: `dist/distributions.js`,
330
332
  `dist/tests.js`, `dist/linalg.js`, `dist/descriptive.js`, `dist/numerics.js`, `dist/special.js`,
331
- `dist/mixed.js`, `dist/regression.js` and `dist/multivariate.js` export the same functions as the subpaths above, and share their common code through
333
+ `dist/mixed.js`, `dist/regression.js`, `dist/multivariate.js`, `dist/timeseries.js` and `dist/causal.js` export the same functions as the subpaths above, and share their common code through
332
334
  `dist/chunks/`, so loading two areas does not load that code twice. With its chunks, one area
333
335
  transfers 39 KB (`special`) to 288 KB (`tests`) gzipped.
334
336
 
335
337
  Use either `dist/rstats.js` or the per-area bundles on one page, not both: they are separate sets of modules, so a
336
338
  page that mixes them loads the common code twice and has two random number states (`setSeed` from one does not seed
337
- the generators of the other). The same holds for `dist/rstats.js` with `dist/mixed.js`, `dist/regression.js` or `dist/multivariate.js`, which bring their own copy
339
+ the generators of the other). The same holds for `dist/rstats.js` with `dist/mixed.js`, `dist/regression.js`, `dist/multivariate.js`, `dist/timeseries.js` or `dist/causal.js`, which bring their own copy
338
340
  of the common code.
339
341
 
340
342
  Other npm-based CDNs work as well, for example `https://esm.sh/@numero-uno-jpn/rstats`. Release tags also contain
@@ -0,0 +1,106 @@
1
+ import type { MatchEstimand, MatchResult } from "./match.js";
2
+ /**
3
+ * The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
4
+ * weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
5
+ * @category Causal inference
6
+ * @example
7
+ * ```ts
8
+ * matchWeights(match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3])); // [1, 1, 1, 1, 0]
9
+ * ```
10
+ */
11
+ export declare function matchWeights(m: MatchResult): number[];
12
+ /** Options of {@link balTab}. Equivalent to the arguments of cobalt's `bal.tab()` for a `Match` object.
13
+ * @category Causal inference
14
+ */
15
+ export interface BalTabOptions {
16
+ /**
17
+ * The result of {@link match}: gives the weights ({@link matchWeights}), the estimand and, with a caliper, the
18
+ * discarded units. Alternative to `weights` and `estimand`.
19
+ */
20
+ match?: MatchResult;
21
+ /** The weights after matching (from {@link matchWeights}); without them only the unadjusted columns are filled. */
22
+ weights?: readonly number[];
23
+ /** The estimand, which chooses the SD of the denominator (default `"ATT"`). */
24
+ estimand?: MatchEstimand;
25
+ /** Binary covariates: `"raw"` difference in proportions (default, as cobalt) or `"std"` standardised. */
26
+ binary?: "raw" | "std";
27
+ }
28
+ /** Result of {@link balTab}: one entry per covariate, in the order given (cobalt's `Balance` table), and the counts.
29
+ * @category Causal inference
30
+ */
31
+ export interface BalTabResult {
32
+ /** Covariate names. */
33
+ rows: string[];
34
+ /** `"Contin."` or `"Binary"` (a covariate with two distinct values, 0 and 1). */
35
+ type: ("Contin." | "Binary")[];
36
+ /** Difference treated − control before matching: standardised (continuous, or binary with `binary: "std"`) or raw. */
37
+ diffUn: number[];
38
+ /** The same after matching (weighted); NaN without weights. */
39
+ diffAdj: number[];
40
+ /** Variance ratio treated / control before matching (NaN for binary covariates). */
41
+ vRatioUn: number[];
42
+ /** The same after matching, with weighted variances; NaN for binary covariates or without weights. */
43
+ vRatioAdj: number[];
44
+ /**
45
+ * Sample sizes of the control and treated groups (cobalt's `Observations`): all (effective sample size, the same as
46
+ * the count), all (unweighted), matched (effective sample size `(sum w)^2 / sum w^2`), matched (unweighted:
47
+ * `w > 0`), unmatched (`w = 0`) and, when `match` has a caliper, discarded (its `indexDropped`, not counted as unmatched). The
48
+ * matched rows are NaN without weights.
49
+ */
50
+ observations: {
51
+ /** Row names, in the order of the counts. */
52
+ rows: string[];
53
+ /** Counts of the control group. */
54
+ control: number[];
55
+ /** Counts of the treated group. */
56
+ treated: number[];
57
+ };
58
+ }
59
+ /**
60
+ * Covariate balance of two groups before and after matching: standardised mean differences and variance ratios.
61
+ * Equivalent to `cobalt::bal.tab()` in R. The call followed is
62
+ * `bal.tab(m, formula = tr ~ ..., data, un = TRUE, disp.v.ratio = TRUE, binary)` for a `Match` object `m`.
63
+ *
64
+ * The difference is `(mean treated − mean control) / s`, with means weighted after matching. The SD `s` is always that
65
+ * of the unmatched sample: of the treated for ATT, of the controls for ATC, `sqrt((s1² + s0²) / 2)` for ATE; for a
66
+ * binary covariate (with `binary: "std"`) `sqrt(p(1 − p))` in place of the SD (the mean of `p1(1 − p1)` and
67
+ * `p0(1 − p0)` for ATE).
68
+ * Variance ratios are treated / control. Factor covariates are not split: give one 0/1 column per level.
69
+ * @category Causal inference
70
+ * @example
71
+ * ```ts
72
+ * const tr = [1, 0, 1, 0, 0, 1, 0, 0];
73
+ * const age = [52, 40, 61, 58, 33, 47, 50, 45];
74
+ * const m = match(tr, [0.4, -0.9, 1.2, 1.0, -1.5, 0.1, 0.3, -0.2]);
75
+ * const b = balTab(tr, { age }, { match: m });
76
+ * b.diffUn; // [1.1464120051932525]
77
+ * b.diffAdj; // [0.32888869001445803]
78
+ * ```
79
+ */
80
+ export declare function balTab(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, readonly number[]>>, options?: BalTabOptions): BalTabResult;
81
+ /** Options of {@link tableOneSmd}.
82
+ * @category Causal inference
83
+ */
84
+ export interface TableOneSmdOptions {
85
+ /** Treat `x` as categorical (tableone's `factorVars`): numbers or strings as levels. Default false. */
86
+ factor?: boolean;
87
+ }
88
+ /**
89
+ * Standardised mean difference of one variable between two groups. Equivalent to `tableone::ExtractSmd()` in R. The
90
+ * call followed is `ExtractSmd(CreateTableOne(vars, strata, data, factorVars))` with two groups. Missing values (`NaN`,
91
+ * `null`) are left out.
92
+ *
93
+ * Numeric: `|mean1 − mean0| / sqrt((s1² + s0²) / 2)` with the groups' SDs (divisor `n − 1`). Categorical
94
+ * (`factor: true`): Yang and Dalton's `sqrt(d' S⁻¹ d)`, `d` the differences of the proportions of the levels after the
95
+ * first, `S` the mean of the two groups' multinomial covariance matrices `p_k (δ_kl − p_l)`; with two levels
96
+ * `|p1 − p0| / sqrt((p1(1 − p1) + p0(1 − p0)) / 2)`. 0 when both the difference and the spread are 0. When `S` is
97
+ * singular (a level in one group only) the generalised inverse is used, as tableone; when `S` is 0 (one level in each
98
+ * group) the result is NaN, as tableone.
99
+ * @category Causal inference
100
+ * @example
101
+ * ```ts
102
+ * tableOneSmd([1, 2, 3, 2, 5, 4], [0, 0, 0, 1, 1, 1]); // 1.2909944487358056
103
+ * tableOneSmd(["a", "b", "a", "b", "b", "b"], [0, 0, 0, 1, 1, 1], { factor: true }); // 2
104
+ * ```
105
+ */
106
+ export declare function tableOneSmd(x: readonly (number | string | null)[], group: readonly (number | string | boolean)[], options?: TableOneSmdOptions): number;
@@ -0,0 +1,216 @@
1
+ // Covariate balance before and after matching: the standardised mean differences and variance ratios of cobalt's
2
+ // bal.tab (for a Match object) and the standardised mean differences of tableone's CreateTableOne / ExtractSmd. The
3
+ // definitions are in oracle/match-behaviour.md, from the packages' documentation and published output; Yang & Dalton
4
+ // (2012), "A unified approach to measuring the effect size between two groups using SAS", SAS Global Forum 335, for
5
+ // the categorical SMD. Written for rStats.js (no ported code).
6
+ import { ginv } from "../linalg/kappa.js";
7
+ import { rescaled } from "./scale.js";
8
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
9
+ import { checkOptions } from "../internal/checkOptions.js";
10
+ const BAL_TAB_KEYS = ["match", "weights", "estimand", "binary"];
11
+ const TABLE_ONE_SMD_KEYS = ["factor"];
12
+ // Generated by `node scripts/option-keys.mjs --write` (end)
13
+ /**
14
+ * The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
15
+ * weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
16
+ * @category Causal inference
17
+ * @example
18
+ * ```ts
19
+ * matchWeights(match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3])); // [1, 1, 1, 1, 0]
20
+ * ```
21
+ */
22
+ export function matchWeights(m) {
23
+ const w = new Array(m.nobs).fill(0);
24
+ m.indexTreated.forEach((t, i) => {
25
+ w[t - 1] += m.weights[i];
26
+ w[m.indexControl[i] - 1] += m.weights[i];
27
+ });
28
+ return w;
29
+ }
30
+ function isTreated(t, i) {
31
+ if (t === true || t === 1)
32
+ return true;
33
+ if (t === false || t === 0)
34
+ return false;
35
+ throw new RangeError(`'tr' must be 0 or 1 (element ${i + 1})`);
36
+ }
37
+ /** Weighted mean and variance (divisor sum(w) - sum(w^2) / sum(w), cobalt's), over the units with g === group. */
38
+ function moments(v, w, g, group) {
39
+ let sw = 0, sw2 = 0, swx = 0;
40
+ for (let i = 0; i < v.length; i++) {
41
+ if (g[i] !== group)
42
+ continue;
43
+ const wi = w === null ? 1 : w[i];
44
+ sw += wi;
45
+ sw2 += wi * wi;
46
+ swx += wi * v[i];
47
+ }
48
+ const mean = swx / sw;
49
+ let ss = 0;
50
+ for (let i = 0; i < v.length; i++) {
51
+ if (g[i] !== group)
52
+ continue;
53
+ const wi = w === null ? 1 : w[i];
54
+ ss += wi * (v[i] - mean) * (v[i] - mean);
55
+ }
56
+ return [mean, ss / (sw - sw2 / sw)];
57
+ }
58
+ /**
59
+ * Covariate balance of two groups before and after matching: standardised mean differences and variance ratios.
60
+ * Equivalent to `cobalt::bal.tab()` in R. The call followed is
61
+ * `bal.tab(m, formula = tr ~ ..., data, un = TRUE, disp.v.ratio = TRUE, binary)` for a `Match` object `m`.
62
+ *
63
+ * The difference is `(mean treated − mean control) / s`, with means weighted after matching. The SD `s` is always that
64
+ * of the unmatched sample: of the treated for ATT, of the controls for ATC, `sqrt((s1² + s0²) / 2)` for ATE; for a
65
+ * binary covariate (with `binary: "std"`) `sqrt(p(1 − p))` in place of the SD (the mean of `p1(1 − p1)` and
66
+ * `p0(1 − p0)` for ATE).
67
+ * Variance ratios are treated / control. Factor covariates are not split: give one 0/1 column per level.
68
+ * @category Causal inference
69
+ * @example
70
+ * ```ts
71
+ * const tr = [1, 0, 1, 0, 0, 1, 0, 0];
72
+ * const age = [52, 40, 61, 58, 33, 47, 50, 45];
73
+ * const m = match(tr, [0.4, -0.9, 1.2, 1.0, -1.5, 0.1, 0.3, -0.2]);
74
+ * const b = balTab(tr, { age }, { match: m });
75
+ * b.diffUn; // [1.1464120051932525]
76
+ * b.diffAdj; // [0.32888869001445803]
77
+ * ```
78
+ */
79
+ export function balTab(tr, covariates, options = {}) {
80
+ checkOptions(options, BAL_TAB_KEYS, "balTab"); // generated: option-keys.mjs
81
+ const { match: m, binary = "raw" } = options;
82
+ const weights = m === undefined ? options.weights : matchWeights(m);
83
+ const estimand = m?.estimand ?? options.estimand ?? "ATT";
84
+ const discarded = new Set(m?.indexDropped ?? []);
85
+ const withDiscarded = m !== undefined && m.caliper !== null;
86
+ const n = tr.length;
87
+ const g = tr.map(isTreated);
88
+ if (!g.includes(true) || !g.includes(false))
89
+ throw new RangeError("'tr' must contain both groups");
90
+ if (weights !== undefined && weights.length !== n)
91
+ throw new RangeError("'weights' must have the length of 'tr'");
92
+ const rows = Object.keys(covariates);
93
+ const result = {
94
+ rows, type: [], diffUn: [], diffAdj: [], vRatioUn: [], vRatioAdj: [],
95
+ observations: {
96
+ rows: ["All (ESS)", "All (Unweighted)", "Matched (ESS)", "Matched (Unweighted)", "Unmatched", ...(withDiscarded ? ["Discarded"] : [])],
97
+ control: [], treated: [],
98
+ },
99
+ };
100
+ for (const name of rows) {
101
+ const v = covariates[name];
102
+ if (v.length !== n)
103
+ throw new RangeError(`covariate '${name}' must have the length of 'tr'`);
104
+ if (v.some((x) => !Number.isFinite(x)))
105
+ throw new RangeError(`covariate '${name}' has missing or infinite values`);
106
+ const isBinary = new Set(v).size <= 2 && v.every((x) => x === 0 || x === 1);
107
+ // a continuous covariate rescaled exactly: its standardised differences and variance ratios do not change
108
+ const vs = isBinary ? v : rescaled(v).values;
109
+ const [m1, var1] = moments(vs, null, g, true);
110
+ const [m0, var0] = moments(vs, null, g, false);
111
+ const spread = isBinary ? [m1 * (1 - m1), m0 * (1 - m0)] : [var1, var0];
112
+ const s = estimand === "ATT" ? Math.sqrt(spread[0]) : estimand === "ATC" ? Math.sqrt(spread[1])
113
+ : Math.sqrt((spread[0] + spread[1]) / 2);
114
+ const scale = isBinary && binary === "raw" ? 1 : s;
115
+ result.type.push(isBinary ? "Binary" : "Contin.");
116
+ // a difference of 0 is 0 (cobalt's, also for a constant covariate whose SD is 0)
117
+ result.diffUn.push(m1 === m0 ? 0 : (m1 - m0) / scale);
118
+ // a zero control variance gives NA in cobalt (not Inf)
119
+ result.vRatioUn.push(isBinary || var0 === 0 ? NaN : var1 / var0);
120
+ if (weights === undefined) {
121
+ result.diffAdj.push(NaN);
122
+ result.vRatioAdj.push(NaN);
123
+ continue;
124
+ }
125
+ const [a1, av1] = moments(vs, weights, g, true);
126
+ const [a0, av0] = moments(vs, weights, g, false);
127
+ result.diffAdj.push(a1 === a0 ? 0 : (a1 - a0) / scale);
128
+ result.vRatioAdj.push(isBinary || av0 === 0 ? NaN : av1 / av0);
129
+ }
130
+ for (const group of [false, true]) {
131
+ let count = 0, sw = 0, sw2 = 0, positive = 0, gone = 0;
132
+ for (let i = 0; i < n; i++) {
133
+ if (g[i] !== group)
134
+ continue;
135
+ count++;
136
+ if (discarded.has(i + 1))
137
+ gone++;
138
+ if (weights === undefined)
139
+ continue;
140
+ const wi = weights[i];
141
+ sw += wi;
142
+ sw2 += wi * wi;
143
+ if (wi > 0)
144
+ positive++;
145
+ }
146
+ const matched = weights === undefined ? [NaN, NaN, NaN] : [sw * sw / sw2, positive, count - positive - gone];
147
+ if (withDiscarded)
148
+ matched.push(gone);
149
+ (group ? result.observations.treated : result.observations.control).push(count, count, ...matched);
150
+ }
151
+ return result;
152
+ }
153
+ /**
154
+ * Standardised mean difference of one variable between two groups. Equivalent to `tableone::ExtractSmd()` in R. The
155
+ * call followed is `ExtractSmd(CreateTableOne(vars, strata, data, factorVars))` with two groups. Missing values (`NaN`,
156
+ * `null`) are left out.
157
+ *
158
+ * Numeric: `|mean1 − mean0| / sqrt((s1² + s0²) / 2)` with the groups' SDs (divisor `n − 1`). Categorical
159
+ * (`factor: true`): Yang and Dalton's `sqrt(d' S⁻¹ d)`, `d` the differences of the proportions of the levels after the
160
+ * first, `S` the mean of the two groups' multinomial covariance matrices `p_k (δ_kl − p_l)`; with two levels
161
+ * `|p1 − p0| / sqrt((p1(1 − p1) + p0(1 − p0)) / 2)`. 0 when both the difference and the spread are 0. When `S` is
162
+ * singular (a level in one group only) the generalised inverse is used, as tableone; when `S` is 0 (one level in each
163
+ * group) the result is NaN, as tableone.
164
+ * @category Causal inference
165
+ * @example
166
+ * ```ts
167
+ * tableOneSmd([1, 2, 3, 2, 5, 4], [0, 0, 0, 1, 1, 1]); // 1.2909944487358056
168
+ * tableOneSmd(["a", "b", "a", "b", "b", "b"], [0, 0, 0, 1, 1, 1], { factor: true }); // 2
169
+ * ```
170
+ */
171
+ export function tableOneSmd(x, group, options = {}) {
172
+ checkOptions(options, TABLE_ONE_SMD_KEYS, "tableOneSmd"); // generated: option-keys.mjs
173
+ const { factor = false } = options;
174
+ if (x.length !== group.length)
175
+ throw new RangeError("'x' and 'group' must have the same length");
176
+ const glev = [...new Set(group)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
177
+ if (glev.length !== 2)
178
+ throw new RangeError("'group' must have exactly two levels");
179
+ const keep = (v) => v !== null && !(typeof v === "number" && Number.isNaN(v));
180
+ const parts = glev.map((lv) => x.filter((v, i) => group[i] === lv && keep(v)));
181
+ if (!factor) {
182
+ if (parts.flat().some((e) => typeof e !== "number"))
183
+ throw new TypeError("'x' must be numeric unless factor: true");
184
+ // rescaled exactly as one column (the SMD does not change)
185
+ const all = rescaled(parts.flat()).values;
186
+ const split = [all.slice(0, parts[0].length), all.slice(parts[0].length)];
187
+ const stats = split.map((v) => {
188
+ const mean = v.reduce((s, e) => s + e, 0) / v.length;
189
+ return [mean, v.reduce((s, e) => s + (e - mean) * (e - mean), 0) / (v.length - 1)];
190
+ });
191
+ const diff = stats[1][0] - stats[0][0];
192
+ const sd = Math.sqrt((stats[0][1] + stats[1][1]) / 2);
193
+ return diff === 0 ? 0 : Math.abs(diff) / sd;
194
+ }
195
+ const levels = [...new Set(parts.flat())].sort((a, b) => (typeof a === "number" && typeof b === "number" ? a - b
196
+ : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0));
197
+ const props = parts.map((p) => levels.slice(1).map((lv) => p.filter((e) => e === lv).length / p.length));
198
+ const d = props[1].map((q, k) => q - props[0][k]);
199
+ if (d.every((e) => e === 0))
200
+ return 0;
201
+ const K = d.length;
202
+ const S = Array.from({ length: K }, (_, k) => Array.from({ length: K }, (_, l) => {
203
+ const c = (p) => (k === l ? p[k] * (1 - p[k]) : -p[k] * p[l]);
204
+ return (c(props[0]) + c(props[1])) / 2;
205
+ }));
206
+ // S is singular when a level is in one group only: tableone's value is then that of the generalised inverse
207
+ // (MASS::ginv's; experiments/psm112-edge.json factorAbsent), and NaN when S is 0 (each group has one level)
208
+ if (S.every((row) => row.every((v) => v === 0)))
209
+ return NaN;
210
+ const Si = ginv(S);
211
+ let q = 0;
212
+ for (let k = 0; k < K; k++)
213
+ for (let l = 0; l < K; l++)
214
+ q += d[k] * Si[k][l] * d[l];
215
+ return Math.sqrt(q);
216
+ }
@@ -0,0 +1,86 @@
1
+ /** The population the matching estimates for: the treated (ATT), everyone (ATE) or the controls (ATC).
2
+ * @category Causal inference
3
+ */
4
+ export type MatchEstimand = "ATT" | "ATE" | "ATC";
5
+ /** Options of {@link match}. Equivalent to the arguments of the Matching package's `Match()` with `ties = FALSE` and
6
+ * `replace = FALSE`.
7
+ * @category Causal inference
8
+ */
9
+ export interface MatchOptions {
10
+ /** The estimand (default `"ATT"`): the treated units are matched (ATT), the controls (ATC), or both (ATE). */
11
+ estimand?: MatchEstimand;
12
+ /** The number of matches for each matched unit (default 1), a positive integer. */
13
+ M?: number;
14
+ /**
15
+ * The caliper in standard deviations of `x` (the SD with divisor n over all units, as R's `ecaliper`): a match
16
+ * farther than `caliper * sd` is not made, and a unit with fewer than `M` controls within it is dropped.
17
+ */
18
+ caliper?: number;
19
+ }
20
+ /** Result of {@link match}. The fields are those of R's `Match` object, with 1-based row numbers.
21
+ * @category Causal inference
22
+ */
23
+ export interface MatchResult {
24
+ /** Rows (1-based) of the treated unit of each pair. */
25
+ indexTreated: number[];
26
+ /** Rows (1-based) of the control unit of each pair. */
27
+ indexControl: number[];
28
+ /** Weight of each pair: `1 / M`. */
29
+ weights: number[];
30
+ /**
31
+ * Rows (1-based) of the dropped units that appear in no pair (R's `index.dropped`), only when a caliper is given;
32
+ * `null` otherwise or when none. Under ATE a dropped unit can still be another unit's match and is then not listed.
33
+ * Without a caliper R lists none even when units are dropped (`ndrops` counts them).
34
+ */
35
+ indexDropped: number[] | null;
36
+ /** The caliper as given (in standard deviations), `null` without one. */
37
+ caliper: number | null;
38
+ /** The caliper on the scale of `x` (R's `ecaliper`), `null` without one. */
39
+ ecaliper: number | null;
40
+ /** Number of units (R's `nobs`). */
41
+ nobs: number;
42
+ /** Number of matched units (R's `wnobs`: units that found their matches). */
43
+ wnobs: number;
44
+ /** Number of matched-for units left without matches, for either reason (R's `ndrops`). */
45
+ ndrops: number;
46
+ /** The estimand. */
47
+ estimand: MatchEstimand;
48
+ /** The number of matches per matched unit. */
49
+ M: number;
50
+ /**
51
+ * Size of each candidate set from which matches were drawn at random (more candidates than needed at equal
52
+ * distance), in the order of the draws. Empty when there were no ties; the pairs are then R's. With sets of 2 only
53
+ * the pairs and the random numbers used are also R's; larger sets are broken by rStats.js's own rule (see
54
+ * {@link match}).
55
+ */
56
+ tieSizes: number[];
57
+ /** Warnings (R's, e.g. when no unit could be matched). */
58
+ warnings: string[];
59
+ }
60
+ /**
61
+ * Nearest-neighbour matching on a scalar score, without replacement and with random tie-breaking. Equivalent to
62
+ * `Matching::Match()` in R. The call followed is
63
+ * `Match(Tr = tr, X = x, estimand, M, caliper, ties = FALSE, replace = FALSE)`, used with the linear predictor
64
+ * `logit(PS)` of a propensity score model.
65
+ *
66
+ * The matched units (the treated for ATT, the controls for ATC, all for ATE) are processed in data order. Each takes
67
+ * its matches from the units of the other group not yet used: every available unit within the M-th smallest distance
68
+ * is a candidate (within the caliper when one is given), and when there are more candidates than M, M of them are
69
+ * drawn at random. A unit with fewer than M available candidates is dropped. Pairs are listed in the order of the
70
+ * matched units, the controls of one treated unit (ATT) in row order.
71
+ *
72
+ * Random draws use rStats.js's generator (`setSeed`): one uniform `u` for each pick, and the candidate at 0-based
73
+ * index `floor(k (1 - u))` among the `k` remaining (in row order) is taken. Without ties no random number is used and
74
+ * the pairs are R's; with sets of two candidates the rule is R's (the second when `u < 0.5`). Known differences from
75
+ * R: larger tie sets are broken differently (R's rule is not documented), and distances count as tied only when
76
+ * exactly equal (R also treats distances within `distance.tolerance = 1e-5` as ties). `M` below 1 is an error (R
77
+ * warns and uses 1).
78
+ * @category Causal inference
79
+ * @example
80
+ * ```ts
81
+ * const m = match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3]);
82
+ * m.indexTreated; // [1, 3]
83
+ * m.indexControl; // [2, 4]
84
+ * ```
85
+ */
86
+ export declare function match(tr: readonly (number | boolean)[], x: readonly number[], options?: MatchOptions): MatchResult;