@numero-uno-jpn/rstats 1.12.0 → 1.14.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 (84) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.ja.md +6 -6
  3. package/README.md +6 -6
  4. package/dist/causal/balance.d.ts +30 -18
  5. package/dist/causal/balance.js +74 -26
  6. package/dist/causal/weightit.d.ts +159 -0
  7. package/dist/causal/weightit.js +491 -0
  8. package/dist/causal.js +2 -2
  9. package/dist/chunks/{chunk-3QOW56EJ.js → chunk-2426YL2X.js} +2 -2
  10. package/dist/chunks/{chunk-JG26HC2H.js → chunk-3746VXPM.js} +2 -2
  11. package/dist/chunks/{chunk-XQSYV3IZ.js → chunk-3DA7CMFN.js} +2 -2
  12. package/dist/chunks/{chunk-O6OMXX5U.js → chunk-3XUHCWLU.js} +1 -1
  13. package/dist/chunks/chunk-4O6XLQBN.js +2 -0
  14. package/dist/chunks/{chunk-CKBUE4FV.js → chunk-62Y36UKH.js} +2 -2
  15. package/dist/chunks/{chunk-NGDBJR3K.js → chunk-6HUTVWPO.js} +2 -2
  16. package/dist/chunks/chunk-6VY3XNAF.js +2 -0
  17. package/dist/chunks/{chunk-7K2LMKZR.js → chunk-7BBIQY4W.js} +2 -2
  18. package/dist/chunks/chunk-7FGVMDJE.js +3 -0
  19. package/dist/chunks/{chunk-2P42OXYW.js → chunk-7VMGP2U7.js} +2 -2
  20. package/dist/chunks/{chunk-YKCZF4ES.js → chunk-A5DZG7FH.js} +2 -2
  21. package/dist/chunks/{chunk-7FXBOYIH.js → chunk-AONDWNMF.js} +2 -2
  22. package/dist/chunks/{chunk-SKQHW2GD.js → chunk-AQHG7BEZ.js} +2 -2
  23. package/dist/chunks/{chunk-NAACMR7H.js → chunk-B6NPCYFO.js} +2 -2
  24. package/dist/chunks/{chunk-WUNTM7PJ.js → chunk-BCXYAILN.js} +2 -2
  25. package/dist/chunks/{chunk-QT32BMYA.js → chunk-CKUBQW2A.js} +2 -2
  26. package/dist/chunks/chunk-D25AVVVI.js +2 -0
  27. package/dist/chunks/{chunk-CHKBDZC4.js → chunk-DZQWGBTW.js} +2 -2
  28. package/dist/chunks/{chunk-HF3QOIZX.js → chunk-EDRBKZ3C.js} +2 -2
  29. package/dist/chunks/{chunk-SZR5HAMB.js → chunk-EWNJT27V.js} +2 -2
  30. package/dist/chunks/{chunk-3QSYPBUM.js → chunk-F6KKW5YN.js} +2 -2
  31. package/dist/chunks/{chunk-T5TE5KCP.js → chunk-FPJ2CWLK.js} +2 -2
  32. package/dist/chunks/{chunk-WSDLT4AR.js → chunk-H5GBKP57.js} +1 -1
  33. package/dist/chunks/{chunk-4B7NEJCE.js → chunk-I2OTBVRK.js} +2 -2
  34. package/dist/chunks/{chunk-ZK7FW5UX.js → chunk-IXFWR3LH.js} +2 -2
  35. package/dist/chunks/chunk-JCGCJT7T.js +2 -0
  36. package/dist/chunks/{chunk-L54WIMTZ.js → chunk-KITNZUYC.js} +2 -2
  37. package/dist/chunks/chunk-MCEZRRQO.js +2 -0
  38. package/dist/chunks/{chunk-UPFMYDF7.js → chunk-MJHFGGPU.js} +2 -2
  39. package/dist/chunks/{chunk-4GRV66HW.js → chunk-MXOBCQQP.js} +2 -2
  40. package/dist/chunks/{chunk-WACTNIKS.js → chunk-NA7EDZ4Q.js} +2 -2
  41. package/dist/chunks/{chunk-SLMS3FQD.js → chunk-PHDTVTKV.js} +1 -1
  42. package/dist/chunks/{chunk-ZHAT6244.js → chunk-QLKZ2OFQ.js} +2 -2
  43. package/dist/chunks/{chunk-MAFZ5FGL.js → chunk-SDIIGAY5.js} +2 -2
  44. package/dist/chunks/{chunk-4U65I4J2.js → chunk-SEKOIW43.js} +2 -2
  45. package/dist/chunks/{chunk-52KGBGFL.js → chunk-TGXUU5NB.js} +1 -1
  46. package/dist/chunks/chunk-VWCCPBBG.js +2 -0
  47. package/dist/chunks/chunk-XXH5OIUO.js +2 -0
  48. package/dist/chunks/{chunk-MJ7IY7AF.js → chunk-Y7VD43TO.js} +2 -2
  49. package/dist/chunks/{chunk-5AR4V7MW.js → chunk-YLUF4WTL.js} +2 -2
  50. package/dist/chunks/{chunk-ULQXNAI6.js → chunk-ZJJJDLRL.js} +2 -2
  51. package/dist/chunks/chunk-ZWSHIUBZ.js +2 -0
  52. package/dist/descriptive.js +2 -2
  53. package/dist/distributions.js +2 -2
  54. package/dist/entries/causal.d.ts +1 -0
  55. package/dist/entries/causal.js +1 -0
  56. package/dist/entries/regression.d.ts +1 -0
  57. package/dist/entries/regression.js +2 -0
  58. package/dist/entries/tests.d.ts +2 -0
  59. package/dist/entries/tests.js +2 -0
  60. package/dist/linalg.js +2 -2
  61. package/dist/mixed.js +2 -2
  62. package/dist/models/multinom.d.ts +250 -0
  63. package/dist/models/multinom.js +520 -0
  64. package/dist/models/survfitCoxph.d.ts +95 -0
  65. package/dist/models/survfitCoxph.js +223 -0
  66. package/dist/models/survival.d.ts +9 -2
  67. package/dist/models/survival.js +15 -11
  68. package/dist/models/svyglm.d.ts +77 -0
  69. package/dist/models/svyglm.js +102 -0
  70. package/dist/multivariate.js +2 -2
  71. package/dist/numerics.js +2 -2
  72. package/dist/regression.js +3 -3
  73. package/dist/rstats.js +17 -17
  74. package/dist/special.js +2 -2
  75. package/dist/tests.js +15 -15
  76. package/dist/timeseries.js +2 -2
  77. package/package.json +1 -1
  78. package/dist/chunks/chunk-7UI4PW32.js +0 -2
  79. package/dist/chunks/chunk-CMTCPLIA.js +0 -2
  80. package/dist/chunks/chunk-DWVTVOQS.js +0 -2
  81. package/dist/chunks/chunk-FFMMKXMK.js +0 -2
  82. package/dist/chunks/chunk-MUYGPZ37.js +0 -3
  83. package/dist/chunks/chunk-NQT7ZWL6.js +0 -2
  84. package/dist/chunks/chunk-PYFASERO.js +0 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,24 @@ 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.14.0 - 2026-11-24
11
+
12
+ ### Added
13
+
14
+ - **Multinomial logistic regression** in `/regression`: `multinom` (after `nnet::multinom`: baseline-category logits, case weights, decay), `multinomSummary` (Wald tests, odds ratios, McFadden's, Cox-Snell's and Nagelkerke's pseudo R²), `multinomConfint`, `multinomPredict` (probabilities and classes, R's tie-breaking), `multinomAnova` (likelihood-ratio tests of nested models) and `multinomVcov`. The coefficients are the exact maximum; R's BFGS stops about 1e-5 from it ([the differences](docs/differences-from-r.md#multinomial-logistic-regression-1140)).
15
+
16
+ ## 1.13.0 - 2026-11-24
17
+
18
+ ### Added
19
+
20
+ - **Inverse probability of treatment weighting** in `/causal`: balancing weights (`weightit`, after `WeightIt::weightit`: methods glm, cbps, ipt and ebal; ATE, ATT, ATC and ATO; stabilized), trimming (`trimWeights`, after `WeightIt::trim`) and the weight summary (`weightSummary`, Kish's effective sample size by group).
21
+ - `balTab` takes a weightit result (the `prop.score` row, factor levels, the ATO denominator).
22
+ - **Weighted analyses**: `svyglm` (after `survey::svyglm` for `svydesign(ids = ~1, weights)`: design-based standard errors and t tests) and `survfitCoxph` (adjusted survival curves of a weighted Cox fit, after `survfit(coxph, newdata)`).
23
+
24
+ ### Changed
25
+
26
+ - `survfit` takes non-integer case weights (inverse probability weights), with the robust variance by default as R; not with `stype: 2` and the robust variance.
27
+
10
28
  ## 1.12.0 - 2026-11-24
11
29
 
12
30
  ### 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.12.0。** R の stats パッケージの数値計算の中心
19
+ 状態: **1.14.0。** R の stats パッケージの数値計算の中心
20
20
  (分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
21
21
  [ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
22
22
 
@@ -219,22 +219,22 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
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
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` |
222
+ | 因果推論 | `match` (傾向スコアのマッチング: `ties = FALSE`・`replace = FALSE` の `Matching::Match`。ATT・ATE・ATC、1:M、キャリパー)、`matchWeights` (`cobalt::get.w`)、`weightit` (逆確率重み: glm・cbps・ipt・ebal の `WeightIt::weightit`。ATE・ATT・ATC・ATO)、`trimWeights`・`weightSummary`、`balTab` (マッチング・重み付けの前後の標準化平均差と分散比: `cobalt::bal.tab`)、`tableOneSmd` (`tableone::ExtractSmd`)、`@numero-uno-jpn/rstats/causal` |
223
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` |
224
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`) |
225
225
  | 分散分析 | formula で呼ぶ `aov` と `aovSummary` (多元、交互作用、共変量、`Error()` の層), `anova` (`anova.lm`。逐次の表とモデルの比較), `Anova` (car の Type II と III), `aovEz` (afex。反復測定と混合計画、Greenhouse-Geisser と Huynh-Feldt の補正、一般化 η² と偏 η²), `mauchlyTest` (`mauchly.test`) |
226
226
  | 効果量と検出力 | `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) |
227
227
  | 試験デザインの標本サイズと検出力 | `epiSsequb`・`epiSsequc`・`epiSsninfb`・`epiSsninfc`・`epiSssupb`・`epiSssupc` (epiR: 比率と平均の同等性・非劣性・優越性)、`powerPaired2x2` (対応のある 2 × 2 表の正確な McNemar 検定の検出力)、`ssizeCT`・`powerCT`・`ssizeEpi`・`powerEpi`・`numDEpi` (生存時間の標本サイズと検出力)、`ph2simon` (Simon の 2 段階デザイン) |
228
228
  | メタアナリシス | `escalc` (効果量と標本分散)、`rma` (等効果・ランダム効果のメタアナリシスとメタ回帰)、`confintRma`・`predictRma`・`regtest` (metafor) |
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) |
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
+ | 線形モデル | `lm` (formula とデータフレーム、または行列で渡す。`summary` の値も返す), `modelMatrix` (`model.matrix`), `confint`, `predict`。`glm` (行列で渡す形。R の `stats` のすべての族とリンク) と `glmSummary` (`summary.glm`)、`svyglm` (逆確率重みに対する `survey::svyglm`: デザインに基づく標準誤差)、`glmResiduals` (4 種類)、`glmHatvalues`、`glmRstandard`、`glmCooksDistance`、`glmPredict` (標準誤差つき)、`glmConfint` (プロファイル尤度、厳密な限界)、`glmAnova` (`anova.glm`)。`vcovHC`、`vcovCL` (sandwich: HC0〜HC5、一元と多元のクラスター)、`coeftest`、`coefci` (lmtest) |
230
+ | 回帰 | `multinom`・`multinomSummary`・`multinomConfint`・`multinomPredict`・`multinomAnova`・`multinomVcov` (nnet: 重みと decay つきの多項ロジスティック回帰)、`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 します |
231
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 します |
232
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`。
233
233
  `@numero-uno-jpn/rstats/mixed` から import する |
234
234
  | ほかの検定 | `leveneTest`、`propTrendTest` (`prop.trend.test`)、`jonckheereTest`、`cochranQTest`、`adTest`、`lillieTest`、`cvmTest`、`sfTest`、`pearsonTest` (car、DescTools、clinfun、nortest)。`tTOST`、`tsumTOST` (TOSTER: 平均の同等性検定と最小効果検定) |
235
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) |
236
236
  | 多重比較 | `dscfAllPairsTest` (Steel-Dwass)、`kwAllPairsDunnTest`、`kwManyOneDunnTest`、`manyOneUTest` (Steel の多対一の順位検定)、`dunnettTest`、`gamesHowellTest`、`tukeyTest` (PMCMRplus)、`dunnTest` (dunn.test)、`glhtDunnett` (multcomp) |
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` (パラメトリックな加速故障時間回帰) |
237
+ | 生存時間解析 | `survdiff` (log-rank と G-rho 族)、`survfit` (Kaplan-Meier と Nelson-Aalen・Fleming-Harrington の累積ハザード、重み (逆確率重みも)、ロバスト標準誤差、信頼区間、中央値、制限平均、計数過程データ)、`rmst2` (非調整・共変量調整の制限平均生存時間と制限平均損失時間)、`coxph` (Cox 回帰。Efron と Breslow のタイ、ケース重み、層、Wald・尤度比・スコア検定、計数過程データ、ロバスト分散と `cluster`)、`survfitCoxph` (Cox の当てはめの共変量の値ごとの調整生存曲線: `survfit(coxph, newdata)`)、`clogit` (マッチした組の条件付きロジスティック回帰: 正確な尤度と近似の尤度)、`coxZph` (比例ハザード性の検定)、`cuminc`・`timepoints` (累積発生率と Gray の検定)、`crr`・`predictCrr` (Fine-Gray 回帰と予測)、`survreg`・`survregPredict`・`survregResiduals` (パラメトリックな加速故障時間回帰) |
238
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 回帰) |
239
239
  | 一致度と信頼性 | `kappa2`、`kappamFleiss`、`icc` (irr)、`ICC` (psych: Shrout と Fleiss の 6 つの形式)、`cronbachAlpha`、`partialR` (psych)、`polychor`、`polyserial` (polycor)、`pbvnorm`、`factanal`、`omega` (McDonald の ω。psych) |
240
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)` など) |
@@ -317,7 +317,7 @@ minify 済みの ES モジュール、gzip で 322 KB) を jsDelivr から読み
317
317
 
318
318
  ```html
319
319
  <script type="module">
320
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.12.0/dist/rstats.js";
320
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.14.0/dist/rstats.js";
321
321
  console.log(pnorm(1.96)); // ≈ 0.9750021049
322
322
  </script>
323
323
  ```
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.12.0.** The goal is to cover the numerical core of R's
17
+ Status: **1.14.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
 
@@ -217,22 +217,22 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
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
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` |
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`), `weightit` (inverse probability weights: `WeightIt::weightit` with glm, cbps, ipt and ebal; ATE, ATT, ATC and ATO), `trimWeights` and `weightSummary`, `balTab` (standardized mean differences and variance ratios before and after: `cobalt::bal.tab`) and `tableOneSmd` (`tableone::ExtractSmd`), from `@numero-uno-jpn/rstats/causal` |
221
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` |
222
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`) |
223
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
224
  | 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) |
225
225
  | Sample size and power for trial designs | `epiSsequb`, `epiSsequc`, `epiSsninfb`, `epiSsninfc`, `epiSssupb`, `epiSssupc` (epiR: equivalence, non-inferiority and superiority for proportions and means), `powerPaired2x2` (exact paired McNemar power), `ssizeCT`, `powerCT`, `ssizeEpi`, `powerEpi`, `numDEpi` (survival sample size and power), `ph2simon` (Simon two-stage designs) |
226
226
  | Meta-analysis | `escalc` (effect sizes and sampling variances), `rma` (equal- and random-effects meta-analysis and meta-regression), `confintRma`, `predictRma`, `regtest` (metafor) |
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) |
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
+ | 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`), `svyglm` (`survey::svyglm` for inverse probability weights: design-based standard errors), `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) |
228
+ | Regression | `multinom`, `multinomSummary`, `multinomConfint`, `multinomPredict`, `multinomAnova`, `multinomVcov` (nnet: multinomial logistic regression with weights and decay), `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` |
229
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` |
230
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
231
231
  `simulateGlmer`, from `@numero-uno-jpn/rstats/mixed` |
232
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) |
233
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) |
234
234
  | Multiple comparisons | `dscfAllPairsTest` (Steel-Dwass), `kwAllPairsDunnTest`, `kwManyOneDunnTest`, `manyOneUTest` (Steel's many-one rank test), `dunnettTest`, `gamesHowellTest`, `tukeyTest` (PMCMRplus), `dunnTest` (dunn.test), `glhtDunnett` (multcomp) |
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) |
235
+ | Survival analysis | `survdiff` (log-rank and the G-rho family), `survfit` (Kaplan-Meier and Nelson-Aalen/Fleming-Harrington cumulative hazards, weights (also inverse probability 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`), `survfitCoxph` (adjusted survival curves of a Cox fit for covariate profiles: `survfit(coxph, newdata)`), `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) |
236
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) |
237
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) |
238
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)`, ...) |
@@ -316,7 +316,7 @@ function except those of `/mixed` and `/regression`, 322 KB gzipped) from jsDeli
316
316
 
317
317
  ```html
318
318
  <script type="module">
319
- import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.12.0/dist/rstats.js";
319
+ import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.14.0/dist/rstats.js";
320
320
  console.log(pnorm(1.96)); // ≈ 0.9750021049
321
321
  </script>
322
322
  ```
@@ -1,4 +1,5 @@
1
- import type { MatchEstimand, MatchResult } from "./match.js";
1
+ import type { MatchResult } from "./match.js";
2
+ import type { WeightitEstimand, WeightitResult } from "./weightit.js";
2
3
  /**
3
4
  * The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
4
5
  * weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
@@ -9,7 +10,7 @@ import type { MatchEstimand, MatchResult } from "./match.js";
9
10
  * ```
10
11
  */
11
12
  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
+ /** Options of {@link balTab}. Equivalent to the arguments of cobalt's `bal.tab()` for a `Match` or `weightit` object.
13
14
  * @category Causal inference
14
15
  */
15
16
  export interface BalTabOptions {
@@ -18,10 +19,17 @@ export interface BalTabOptions {
18
19
  * discarded units. Alternative to `weights` and `estimand`.
19
20
  */
20
21
  match?: MatchResult;
21
- /** The weights after matching (from {@link matchWeights}); without them only the unadjusted columns are filled. */
22
+ /**
23
+ * The result of {@link weightit}: gives the weights, the estimand and the propensity score (the first row,
24
+ * `"prop.score"`, when the method has one). Alternative to `match`, `weights` and `estimand`.
25
+ */
26
+ weightit?: WeightitResult;
27
+ /** The weights after matching or weighting; without them only the unadjusted columns are filled. */
22
28
  weights?: readonly number[];
23
- /** The estimand, which chooses the SD of the denominator (default `"ATT"`). */
24
- estimand?: MatchEstimand;
29
+ /** The estimand, which chooses the SD of the denominator (default `"ATT"`); `"ATO"` needs the weights. */
30
+ estimand?: WeightitEstimand;
31
+ /** The order of the levels of string covariates (R's factor levels); default code-point order. */
32
+ levels?: Readonly<Record<string, readonly string[]>>;
25
33
  /** Binary covariates: `"raw"` difference in proportions (default, as cobalt) or `"std"` standardised. */
26
34
  binary?: "raw" | "std";
27
35
  }
@@ -29,10 +37,11 @@ export interface BalTabOptions {
29
37
  * @category Causal inference
30
38
  */
31
39
  export interface BalTabResult {
32
- /** Covariate names. */
40
+ /** Covariate names (`"prop.score"` first for a weightit result with a score; a string covariate gives a row
41
+ * `name_level` per level, one row for the second level when it has two). */
33
42
  rows: string[];
34
- /** `"Contin."` or `"Binary"` (a covariate with two distinct values, 0 and 1). */
35
- type: ("Contin." | "Binary")[];
43
+ /** `"Distance"` (the propensity score), `"Contin."` or `"Binary"` (two distinct values, 0 and 1). */
44
+ type: ("Distance" | "Contin." | "Binary")[];
36
45
  /** Difference treated − control before matching: standardised (continuous, or binary with `binary: "std"`) or raw. */
37
46
  diffUn: number[];
38
47
  /** The same after matching (weighted); NaN without weights. */
@@ -45,7 +54,8 @@ export interface BalTabResult {
45
54
  * Sample sizes of the control and treated groups (cobalt's `Observations`): all (effective sample size, the same as
46
55
  * the count), all (unweighted), matched (effective sample size `(sum w)^2 / sum w^2`), matched (unweighted:
47
56
  * `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.
57
+ * matched rows are NaN without weights. For a weightit result: unadjusted (the count)
58
+ * and adjusted (the effective sample size).
49
59
  */
50
60
  observations: {
51
61
  /** Row names, in the order of the counts. */
@@ -57,15 +67,17 @@ export interface BalTabResult {
57
67
  };
58
68
  }
59
69
  /**
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`.
70
+ * Covariate balance of two groups before and after matching or weighting: standardised mean differences and variance
71
+ * ratios. Equivalent to `cobalt::bal.tab()` in R. The calls followed are
72
+ * `bal.tab(m, formula = tr ~ ..., data, un = TRUE, disp.v.ratio = TRUE, binary)` for a `Match` object `m` and
73
+ * `bal.tab(w, stats = c("mean.diffs", "variance.ratios"), un = TRUE, binary)` for a `weightit` object `w`.
63
74
  *
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.
75
+ * The difference is `(mean treated − mean control) / s`, with means weighted after adjustment. The SD `s` is the same
76
+ * before and after: of the unadjusted treated for ATT, of the unadjusted controls for ATC, `sqrt((s1² + s0²) / 2)` for
77
+ * ATE; for ATO that of the whole sample weighted by the (overlap) weights (weighted variance with divisor
78
+ * `sum w − sum w² / sum w`). For a binary covariate (with `binary: "std"`) `p(1 − p)` takes the place of the variance.
79
+ * As cobalt, an SD below sqrt(eps) ≈ 1.5e-8 (in the covariate's units) is replaced by that of the whole sample.
80
+ * Variance ratios are treated / control. A string covariate is a factor: one binary row per level.
69
81
  * @category Causal inference
70
82
  * @example
71
83
  * ```ts
@@ -77,7 +89,7 @@ export interface BalTabResult {
77
89
  * b.diffAdj; // [0.32888869001445803]
78
90
  * ```
79
91
  */
80
- export declare function balTab(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, readonly number[]>>, options?: BalTabOptions): BalTabResult;
92
+ export declare function balTab(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, readonly number[] | readonly string[]>>, options?: BalTabOptions): BalTabResult;
81
93
  /** Options of {@link tableOneSmd}.
82
94
  * @category Causal inference
83
95
  */
@@ -4,10 +4,12 @@
4
4
  // (2012), "A unified approach to measuring the effect size between two groups using SAS", SAS Global Forum 335, for
5
5
  // the categorical SMD. Written for rStats.js (no ported code).
6
6
  import { ginv } from "../linalg/kappa.js";
7
+ import { compareCodePoints } from "../models/modelFrame.js";
7
8
  import { rescaled } from "./scale.js";
9
+ import { ldexp } from "../internal/summary.js";
8
10
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
9
11
  import { checkOptions } from "../internal/checkOptions.js";
10
- const BAL_TAB_KEYS = ["match", "weights", "estimand", "binary"];
12
+ const BAL_TAB_KEYS = ["match", "weightit", "weights", "estimand", "levels", "binary"];
11
13
  const TABLE_ONE_SMD_KEYS = ["factor"];
12
14
  // Generated by `node scripts/option-keys.mjs --write` (end)
13
15
  /**
@@ -56,15 +58,17 @@ function moments(v, w, g, group) {
56
58
  return [mean, ss / (sw - sw2 / sw)];
57
59
  }
58
60
  /**
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`.
61
+ * Covariate balance of two groups before and after matching or weighting: standardised mean differences and variance
62
+ * ratios. Equivalent to `cobalt::bal.tab()` in R. The calls followed are
63
+ * `bal.tab(m, formula = tr ~ ..., data, un = TRUE, disp.v.ratio = TRUE, binary)` for a `Match` object `m` and
64
+ * `bal.tab(w, stats = c("mean.diffs", "variance.ratios"), un = TRUE, binary)` for a `weightit` object `w`.
62
65
  *
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.
66
+ * The difference is `(mean treated − mean control) / s`, with means weighted after adjustment. The SD `s` is the same
67
+ * before and after: of the unadjusted treated for ATT, of the unadjusted controls for ATC, `sqrt((s1² + s0²) / 2)` for
68
+ * ATE; for ATO that of the whole sample weighted by the (overlap) weights (weighted variance with divisor
69
+ * `sum w − sum w² / sum w`). For a binary covariate (with `binary: "std"`) `p(1 − p)` takes the place of the variance.
70
+ * As cobalt, an SD below sqrt(eps) ≈ 1.5e-8 (in the covariate's units) is replaced by that of the whole sample.
71
+ * Variance ratios are treated / control. A string covariate is a factor: one binary row per level.
68
72
  * @category Causal inference
69
73
  * @example
70
74
  * ```ts
@@ -78,9 +82,11 @@ function moments(v, w, g, group) {
78
82
  */
79
83
  export function balTab(tr, covariates, options = {}) {
80
84
  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";
85
+ const { match: m, weightit: wi, binary = "raw", levels = {} } = options;
86
+ if (m !== undefined && wi !== undefined)
87
+ throw new RangeError("give 'match' or 'weightit', not both");
88
+ const weights = m !== undefined ? matchWeights(m) : wi !== undefined ? wi.weights : options.weights;
89
+ const estimand = m?.estimand ?? wi?.estimand ?? options.estimand ?? "ATT";
84
90
  const discarded = new Set(m?.indexDropped ?? []);
85
91
  const withDiscarded = m !== undefined && m.caliper !== null;
86
92
  const n = tr.length;
@@ -89,30 +95,67 @@ export function balTab(tr, covariates, options = {}) {
89
95
  throw new RangeError("'tr' must contain both groups");
90
96
  if (weights !== undefined && weights.length !== n)
91
97
  throw new RangeError("'weights' must have the length of 'tr'");
92
- const rows = Object.keys(covariates);
98
+ if (estimand === "ATO" && weights === undefined)
99
+ throw new RangeError("estimand 'ATO' needs the weights");
100
+ // the rows: the propensity score, then the covariates with a string covariate split into its levels
101
+ const columns = [];
102
+ if (wi?.ps)
103
+ columns.push(["prop.score", wi.ps, "Distance"]);
104
+ for (const [name, col] of Object.entries(covariates)) {
105
+ if (col.length !== n)
106
+ throw new RangeError(`covariate '${name}' must have the length of 'tr'`);
107
+ if (col.every((x) => typeof x === "number")) {
108
+ columns.push([name, col, null]);
109
+ continue;
110
+ }
111
+ if (!col.every((x) => typeof x === "string"))
112
+ throw new TypeError(`covariate '${name}' must be all numbers or all strings`);
113
+ const lev = levels[name] ?? [...new Set(col)].sort(compareCodePoints);
114
+ if (col.some((x) => !lev.includes(x)))
115
+ throw new RangeError(`covariate '${name}' has values not among its levels`);
116
+ // cobalt shows a two-level factor as its second level only
117
+ for (const lv of lev.length === 2 ? lev.slice(1) : lev)
118
+ columns.push([`${name}_${lv}`, col.map((x) => (x === lv ? 1 : 0)), null]);
119
+ }
120
+ const everyone = g.map(() => true);
121
+ const adjustedRows = wi !== undefined;
93
122
  const result = {
94
- rows, type: [], diffUn: [], diffAdj: [], vRatioUn: [], vRatioAdj: [],
123
+ rows: columns.map(([name]) => name), type: [], diffUn: [], diffAdj: [], vRatioUn: [], vRatioAdj: [],
95
124
  observations: {
96
- rows: ["All (ESS)", "All (Unweighted)", "Matched (ESS)", "Matched (Unweighted)", "Unmatched", ...(withDiscarded ? ["Discarded"] : [])],
125
+ rows: adjustedRows ? ["Unadjusted", "Adjusted"]
126
+ : ["All (ESS)", "All (Unweighted)", "Matched (ESS)", "Matched (Unweighted)", "Unmatched", ...(withDiscarded ? ["Discarded"] : [])],
97
127
  control: [], treated: [],
98
128
  },
99
129
  };
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'`);
130
+ for (const [name, v, kind] of columns) {
104
131
  if (v.some((x) => !Number.isFinite(x)))
105
132
  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);
133
+ const isBinary = kind === null && new Set(v).size <= 2 && v.every((x) => x === 0 || x === 1);
107
134
  // a continuous covariate rescaled exactly: its standardised differences and variance ratios do not change
108
- const vs = isBinary ? v : rescaled(v).values;
135
+ const r = isBinary ? null : rescaled(v);
136
+ const vs = r === null ? v : r.values;
109
137
  const [m1, var1] = moments(vs, null, g, true);
110
138
  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);
139
+ let s;
140
+ if (estimand === "ATO") {
141
+ // the SD of the whole sample under the overlap weights
142
+ const [mw, vw] = moments(vs, weights, everyone, true);
143
+ s = Math.sqrt(isBinary ? mw * (1 - mw) : vw);
144
+ }
145
+ else {
146
+ const spread = isBinary ? [m1 * (1 - m1), m0 * (1 - m0)] : [var1, var0];
147
+ s = estimand === "ATT" ? Math.sqrt(spread[0]) : estimand === "ATC" ? Math.sqrt(spread[1])
148
+ : Math.sqrt((spread[0] + spread[1]) / 2);
149
+ // cobalt's: an SD below sqrt(eps) in the covariate's own units (an absolute threshold, as R; so the result
150
+ // depends on the scale there) is replaced by the SD of the whole sample (divisor n - 1)
151
+ // (experiments/iptw113-edge3.json)
152
+ if (ldexp(s, r?.unitExp ?? 0) < Math.sqrt(Number.EPSILON)) {
153
+ const [ma, va] = moments(vs, null, everyone, true);
154
+ s = Math.sqrt(isBinary ? ma * (1 - ma) : va);
155
+ }
156
+ }
114
157
  const scale = isBinary && binary === "raw" ? 1 : s;
115
- result.type.push(isBinary ? "Binary" : "Contin.");
158
+ result.type.push(kind ?? (isBinary ? "Binary" : "Contin."));
116
159
  // a difference of 0 is 0 (cobalt's, also for a constant covariate whose SD is 0)
117
160
  result.diffUn.push(m1 === m0 ? 0 : (m1 - m0) / scale);
118
161
  // a zero control variance gives NA in cobalt (not Inf)
@@ -143,10 +186,15 @@ export function balTab(tr, covariates, options = {}) {
143
186
  if (wi > 0)
144
187
  positive++;
145
188
  }
189
+ const side = group ? result.observations.treated : result.observations.control;
190
+ if (adjustedRows) {
191
+ side.push(count, sw * sw / sw2);
192
+ continue;
193
+ }
146
194
  const matched = weights === undefined ? [NaN, NaN, NaN] : [sw * sw / sw2, positive, count - positive - gone];
147
195
  if (withDiscarded)
148
196
  matched.push(gone);
149
- (group ? result.observations.treated : result.observations.control).push(count, count, ...matched);
197
+ side.push(count, count, ...matched);
150
198
  }
151
199
  return result;
152
200
  }
@@ -0,0 +1,159 @@
1
+ /** The estimand of {@link weightit}: the population whose average treatment effect the weights target.
2
+ * @category Causal inference
3
+ */
4
+ export type WeightitEstimand = "ATE" | "ATT" | "ATC" | "ATO";
5
+ /** The method of {@link weightit} (WeightIt's `method`; `"ps"` is an alias of `"glm"`).
6
+ * @category Causal inference
7
+ */
8
+ export type WeightitMethod = "glm" | "ps" | "cbps" | "ipt" | "ebal";
9
+ /** Options of {@link weightit}. Equivalent to the arguments of WeightIt's `weightit()`.
10
+ * @category Causal inference
11
+ */
12
+ export interface WeightitOptions {
13
+ /** How the weights are estimated (default `"glm"`): see {@link weightit}. */
14
+ method?: WeightitMethod;
15
+ /** The link of the propensity score model: `"logit"` (default), `"probit"`, `"cauchit"` or `"cloglog"` for glm,
16
+ * `"logit"` or `"probit"` for cbps, `"logit"` for ipt; ebal has none. */
17
+ link?: "logit" | "probit" | "cauchit" | "cloglog";
18
+ /** The estimand (default `"ATE"`). ipt and ebal do not allow `"ATO"`. */
19
+ estimand?: WeightitEstimand;
20
+ /** Multiply the weights by the share of the unit's group in the sample (glm with ATE only; ignored with a warning
21
+ * by the other methods, an error with another estimand, as R). Default false. */
22
+ stabilize?: boolean;
23
+ }
24
+ /** Result of {@link weightit}.
25
+ * @category Causal inference
26
+ */
27
+ export interface WeightitResult {
28
+ /** The weights, one per unit, in the order of `tr`. */
29
+ weights: number[];
30
+ /** The propensity scores (null for ebal, which has none): for ipt the score of the tilting that weights the unit's
31
+ * group (ATE), or of the weighted group for all units (ATT: the controls' tilting; ATC: the treated's). */
32
+ ps: number[] | null;
33
+ /** The treatment, 0 or 1 per unit. */
34
+ treat: number[];
35
+ /** The estimand. */
36
+ estimand: WeightitEstimand;
37
+ /** The method as R reports it (`"glm"` for `"ps"`). */
38
+ method: "glm" | "cbps" | "ipt" | "ebal";
39
+ /** The link (null for ebal). */
40
+ link: string | null;
41
+ /** Whether the weights were stabilised. */
42
+ stabilized: boolean;
43
+ /** The focal group of ATT (`1`) and ATC (`0`), null otherwise: its weights are 1. */
44
+ focal: 0 | 1 | null;
45
+ /** The columns of the model matrix after the intercept: the numeric covariates and, for a string covariate, one 0/1
46
+ * column per level after the first (R's treatment contrasts, levels in code-point order). */
47
+ columnNames: string[];
48
+ /** Whether the estimation converged (the glm, or the solution of the balance conditions). */
49
+ converged: boolean;
50
+ /** R's warnings, each once. */
51
+ warnings: string[];
52
+ }
53
+ /** A covariate: numbers, or strings (a factor with its levels in code-point order).
54
+ * @category Causal inference
55
+ */
56
+ export type CovariateColumn = readonly number[] | readonly string[];
57
+ /** The model matrix without its intercept: one column per numeric covariate, k - 1 indicator columns per factor */
58
+ export declare function covariateColumns(covariates: Readonly<Record<string, CovariateColumn>>, n: number): {
59
+ names: string[];
60
+ columns: number[][];
61
+ factors: Record<string, string[]>;
62
+ };
63
+ /**
64
+ * Balancing weights for a binary treatment. Equivalent to `WeightIt::weightit()` in R. The call followed is
65
+ * `weightit(tr ~ covariates, data, method, link, estimand, stabilize)`.
66
+ *
67
+ * - `"glm"` (`"ps"`): the propensity score `p` of a binomial glm with the link, and the weights 1/p and 1/(1 − p)
68
+ * (ATE), 1 and p/(1 − p) (ATT), (1 − p)/p and 1 (ATC), 1 − p and p (ATO, the overlap weights).
69
+ * - `"cbps"`: the just-identified covariate balancing propensity score: the score whose weights (the same formulas)
70
+ * make the weighted means of every covariate column equal in the two groups (ATT: the controls' to the treated's).
71
+ * - `"ipt"`: inverse probability tilting, a logistic score per weighted group whose weights move the group's means to
72
+ * the target (ATE: the whole sample's). Not ATO.
73
+ * - `"ebal"`: entropy balancing: the weights closest to uniform in entropy with the target means, summing to the
74
+ * target size. No propensity score; not ATO.
75
+ *
76
+ * cbps, ipt and ebal are solved exactly (Newton's method on the balance conditions); R stops its optimisers earlier, so
77
+ * those weights agree with R's to about 1e-8 relative. A string covariate is a factor (levels in code-point order);
78
+ * missing values are an error (R drops or imputes them depending on the method).
79
+ * @category Causal inference
80
+ * @example
81
+ * ```ts
82
+ * const tr = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0];
83
+ * const age = [52, 40, 61, 58, 33, 47, 50, 45, 39, 44];
84
+ * const w = weightit(tr, { age }, { estimand: "ATE" });
85
+ * w.ps[0]; // 0.48529828581084455
86
+ * w.weights[0]; // 2.0605883623289194 (1 / ps for a treated unit)
87
+ * ```
88
+ */
89
+ export declare function weightit(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, CovariateColumn>>, options?: WeightitOptions): WeightitResult;
90
+ /** Options of {@link trimWeights}. Equivalent to the arguments of WeightIt's `trim()`.
91
+ * @category Causal inference
92
+ */
93
+ export interface TrimWeightsOptions {
94
+ /** Below 1: the quantile (type 3) of the weights at which they are capped (0.99 caps the top 1%; below 0.5 it is
95
+ * read as 1 − `at`, as R); 1 or more: the number of largest weights set to the next largest (above half the units it
96
+ * is read as the number of units less `at`; as many as the units or more: no trimming, with R's warning). */
97
+ at: number;
98
+ /** Also raise the weights below the quantile 1 − `at` (or the `at` smallest) to it. Default false. */
99
+ lower?: boolean;
100
+ /** For a plain vector of weights: the treatment (only informative with a focal group, which a vector has not). */
101
+ treat?: readonly (number | boolean)[];
102
+ }
103
+ /**
104
+ * Trims (winsorises) extreme weights: those above a quantile, and with `lower` those below the opposite one, are set to
105
+ * it. Equivalent to `WeightIt::trim()` in R. The call followed is `trim(w, at, lower = TRUE)` for a weightit result or a
106
+ * vector of weights.
107
+ *
108
+ * The quantile is R's type 3 of the weights that are not fixed by the estimand: all units for ATE and ATO, the controls
109
+ * for ATT, the treated for ATC. The other weights do not change (no renormalisation). For a weightit result the
110
+ * returned object is a copy with the trimmed weights.
111
+ * @category Causal inference
112
+ */
113
+ export declare function trimWeights(w: WeightitResult, options: TrimWeightsOptions): WeightitResult;
114
+ export declare function trimWeights(w: readonly number[], options: TrimWeightsOptions): number[];
115
+ /** One group's part of {@link weightSummary}.
116
+ * @category Causal inference
117
+ */
118
+ export interface WeightSummaryGroup {
119
+ /** Smallest and largest weight. */
120
+ range: [number, number];
121
+ /** The (up to) 5 largest weights in increasing order; among equal weights the earliest units, as R lists them. */
122
+ top: {
123
+ /** The units (1-based). */
124
+ index: number[];
125
+ /** Their weights. */
126
+ weights: number[];
127
+ };
128
+ /** Mean weight (R prints it for stabilised weights only). */
129
+ mean: number;
130
+ /** Coefficient of variation: SD (divisor n − 1) / mean. */
131
+ coefOfVar: number;
132
+ /** Mean absolute deviation of w / mean(w) from 1. */
133
+ scaledMad: number;
134
+ /** Mean of r log r, r = w / mean(w). */
135
+ negativeEntropy: number;
136
+ /** Number of zero weights (below 1e-10, as R counts them). */
137
+ numZeros: number;
138
+ /** Number of units. */
139
+ n: number;
140
+ /** Kish's effective sample size (sum w)² / sum w². */
141
+ ess: number;
142
+ }
143
+ /** Result of {@link weightSummary}.
144
+ * @category Causal inference
145
+ */
146
+ export interface WeightSummaryResult {
147
+ /** The treated group's summary. */
148
+ treated: WeightSummaryGroup;
149
+ /** The control group's summary. */
150
+ control: WeightSummaryGroup;
151
+ /** Whether the weights were stabilised (R shows the mean weights then). */
152
+ stabilized: boolean;
153
+ }
154
+ /**
155
+ * Summary of balancing weights by group: range, largest weights, coefficient of variation, scaled MAD, negative
156
+ * entropy, zeros and Kish's effective sample size. Equivalent to `WeightIt::summary.weightit()` in R.
157
+ * @category Causal inference
158
+ */
159
+ export declare function weightSummary(w: WeightitResult): WeightSummaryResult;