@numero-uno-jpn/rstats 1.11.0 → 1.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.ja.md +7 -6
- package/README.md +7 -6
- package/dist/causal/balance.d.ts +118 -0
- package/dist/causal/balance.js +264 -0
- package/dist/causal/match.d.ts +86 -0
- package/dist/causal/match.js +155 -0
- package/dist/causal/scale.d.ts +8 -0
- package/dist/causal/scale.js +26 -0
- package/dist/causal/weightit.d.ts +159 -0
- package/dist/causal/weightit.js +491 -0
- package/dist/causal.js +2 -0
- package/dist/chunks/{chunk-ZW5OCUIY.js → chunk-24UIPUSE.js} +1 -1
- package/dist/chunks/{chunk-JD6JHIVV.js → chunk-2BXB6DRK.js} +1 -1
- package/dist/chunks/chunk-2N7PIFPJ.js +2 -0
- package/dist/chunks/{chunk-IRO6MXW2.js → chunk-2SOBG73L.js} +2 -2
- package/dist/chunks/{chunk-PF6LEBKO.js → chunk-3T4TVNXS.js} +2 -2
- package/dist/chunks/chunk-5Y425VAJ.js +2 -0
- package/dist/chunks/{chunk-3K5KP3M2.js → chunk-7V6FRF32.js} +2 -2
- package/dist/chunks/chunk-7ZKPFHAO.js +2 -0
- package/dist/chunks/{chunk-MJLK2RIQ.js → chunk-AH6IVJRF.js} +1 -1
- package/dist/chunks/{chunk-W27XXELU.js → chunk-C7NEFIAH.js} +2 -2
- package/dist/chunks/{chunk-OG5FTIWF.js → chunk-CAOEREY3.js} +2 -2
- package/dist/chunks/{chunk-HIPKYBZ3.js → chunk-CBAEKGP7.js} +2 -2
- package/dist/chunks/{chunk-6VIOWV53.js → chunk-CCYGRSQW.js} +2 -2
- package/dist/chunks/{chunk-46DELNLN.js → chunk-CEY7FHMZ.js} +2 -2
- package/dist/chunks/{chunk-Z6UI6ON2.js → chunk-CKQOWTX7.js} +2 -2
- package/dist/chunks/chunk-CSZCDPF3.js +2 -0
- package/dist/chunks/chunk-DQ2MIFRQ.js +2 -0
- package/dist/chunks/{chunk-XLBSUUWY.js → chunk-DZLOU6HK.js} +2 -2
- package/dist/chunks/{chunk-S5JZMHAW.js → chunk-EWJS4VYF.js} +2 -2
- package/dist/chunks/{chunk-KICTA3JY.js → chunk-GQ4HYF4L.js} +2 -2
- package/dist/chunks/chunk-GRXOLZ6J.js +2 -0
- package/dist/chunks/{chunk-BA32XHDA.js → chunk-IIKFLH2E.js} +2 -2
- package/dist/chunks/{chunk-M4SLTLOX.js → chunk-JJGRQ22M.js} +2 -2
- package/dist/chunks/chunk-JTARV4D3.js +2 -0
- package/dist/chunks/{chunk-OWOBNS75.js → chunk-KOF2HBUV.js} +2 -2
- package/dist/chunks/{chunk-BKH5GQNA.js → chunk-LS55YUPZ.js} +2 -2
- package/dist/chunks/chunk-M3LK23YR.js +2 -0
- package/dist/chunks/{chunk-BNHMQU7V.js → chunk-NRBTDLVW.js} +2 -2
- package/dist/chunks/{chunk-HCHZ6M34.js → chunk-NWWY2WMF.js} +2 -2
- package/dist/chunks/{chunk-TNU4SMV3.js → chunk-OVJU5WCL.js} +2 -2
- package/dist/chunks/{chunk-WHKUEZQI.js → chunk-OWD2GUXJ.js} +2 -2
- package/dist/chunks/{chunk-BZBPPRSH.js → chunk-P2UT6OCU.js} +2 -2
- package/dist/chunks/{chunk-XKQSKVCL.js → chunk-P6HSXCGZ.js} +2 -2
- package/dist/chunks/{chunk-YPDFCKL4.js → chunk-QWXSJEDI.js} +2 -2
- package/dist/chunks/{chunk-QRUQEJJ5.js → chunk-RGEW3YLB.js} +2 -2
- package/dist/chunks/{chunk-BGY7Y3P4.js → chunk-ST6I33C6.js} +1 -1
- package/dist/chunks/{chunk-W2D6IDBY.js → chunk-TQ4P6W3P.js} +2 -2
- package/dist/chunks/chunk-TTBKW2KL.js +2 -0
- package/dist/chunks/{chunk-EV7ZQC6D.js → chunk-UMLJFZJ5.js} +2 -2
- package/dist/chunks/{chunk-NO675KX4.js → chunk-VO65CBCV.js} +2 -2
- package/dist/chunks/{chunk-DMT423BG.js → chunk-XRB552MP.js} +2 -2
- package/dist/chunks/{chunk-JFZOKMZA.js → chunk-XRBNTYQW.js} +2 -2
- package/dist/chunks/{chunk-Y2SS3GX2.js → chunk-Y4UWFH4Q.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/causal.d.ts +3 -0
- package/dist/entries/causal.js +4 -0
- package/dist/entries/tests.d.ts +3 -0
- package/dist/entries/tests.js +3 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/clogit.d.ts +80 -0
- package/dist/models/clogit.js +211 -0
- package/dist/models/coxph.d.ts +9 -0
- package/dist/models/coxph.js +3 -3
- package/dist/models/survfitCoxph.d.ts +95 -0
- package/dist/models/survfitCoxph.js +223 -0
- package/dist/models/survival.d.ts +9 -2
- package/dist/models/survival.js +15 -11
- package/dist/models/svyglm.d.ts +77 -0
- package/dist/models/svyglm.js +102 -0
- package/dist/multivariate.js +2 -2
- package/dist/numerics.js +2 -2
- package/dist/regression.js +2 -2
- package/dist/rstats.js +18 -18
- package/dist/special.js +2 -2
- package/dist/tests.js +15 -15
- package/dist/timeseries.js +2 -2
- package/package.json +6 -1
- package/dist/chunks/chunk-HPWRADJM.js +0 -2
- package/dist/chunks/chunk-JWMVP7XO.js +0 -2
- package/dist/chunks/chunk-P23KCD67.js +0 -2
- package/dist/chunks/chunk-QY4OBLXK.js +0 -2
- package/dist/chunks/chunk-SV6SLUVB.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,26 @@ 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.13.0 - 2026-11-24
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **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).
|
|
15
|
+
- `balTab` takes a weightit result (the `prop.score` row, factor levels, the ATO denominator).
|
|
16
|
+
- **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)`).
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- `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.
|
|
21
|
+
|
|
22
|
+
## 1.12.0 - 2026-11-24
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- **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`).
|
|
27
|
+
- **Conditional logistic regression** (`clogit`, after `survival::clogit`): the exact conditional likelihood and the approximate (Breslow) one.
|
|
28
|
+
- 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)).
|
|
29
|
+
|
|
10
30
|
## 1.11.0 - 2026-11-24
|
|
11
31
|
|
|
12
32
|
### 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.
|
|
19
|
+
状態: **1.13.0。** R の stats パッケージの数値計算の中心
|
|
20
20
|
(分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
|
|
21
21
|
[ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
|
|
22
22
|
|
|
@@ -219,13 +219,14 @@ 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`)、`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` |
|
|
222
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` |
|
|
223
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`) |
|
|
224
225
|
| 分散分析 | formula で呼ぶ `aov` と `aovSummary` (多元、交互作用、共変量、`Error()` の層), `anova` (`anova.lm`。逐次の表とモデルの比較), `Anova` (car の Type II と III), `aovEz` (afex。反復測定と混合計画、Greenhouse-Geisser と Huynh-Feldt の補正、一般化 η² と偏 η²), `mauchlyTest` (`mauchly.test`) |
|
|
225
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) |
|
|
226
227
|
| 試験デザインの標本サイズと検出力 | `epiSsequb`・`epiSsequc`・`epiSsninfb`・`epiSsninfc`・`epiSssupb`・`epiSssupc` (epiR: 比率と平均の同等性・非劣性・優越性)、`powerPaired2x2` (対応のある 2 × 2 表の正確な McNemar 検定の検出力)、`ssizeCT`・`powerCT`・`ssizeEpi`・`powerEpi`・`numDEpi` (生存時間の標本サイズと検出力)、`ph2simon` (Simon の 2 段階デザイン) |
|
|
227
228
|
| メタアナリシス | `escalc` (効果量と標本分散)、`rma` (等効果・ランダム効果のメタアナリシスとメタ回帰)、`confintRma`・`predictRma`・`regtest` (metafor) |
|
|
228
|
-
| 線形モデル | `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) |
|
|
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) |
|
|
229
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 します |
|
|
230
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 します |
|
|
231
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,7 +234,7 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
|
|
|
233
234
|
| ほかの検定 | `leveneTest`、`propTrendTest` (`prop.trend.test`)、`jonckheereTest`、`cochranQTest`、`adTest`、`lillieTest`、`cvmTest`、`sfTest`、`pearsonTest` (car、DescTools、clinfun、nortest)。`tTOST`、`tsumTOST` (TOSTER: 平均の同等性検定と最小効果検定) |
|
|
234
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) |
|
|
235
236
|
| 多重比較 | `dscfAllPairsTest` (Steel-Dwass)、`kwAllPairsDunnTest`、`kwManyOneDunnTest`、`manyOneUTest` (Steel の多対一の順位検定)、`dunnettTest`、`gamesHowellTest`、`tukeyTest` (PMCMRplus)、`dunnTest` (dunn.test)、`glhtDunnett` (multcomp) |
|
|
236
|
-
| 生存時間解析 | `survdiff` (log-rank と G-rho 族)、`survfit` (Kaplan-Meier と Nelson-Aalen・Fleming-Harrington
|
|
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` (パラメトリックな加速故障時間回帰) |
|
|
237
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 回帰) |
|
|
238
239
|
| 一致度と信頼性 | `kappa2`、`kappamFleiss`、`icc` (irr)、`ICC` (psych: Shrout と Fleiss の 6 つの形式)、`cronbachAlpha`、`partialR` (psych)、`polychor`、`polyserial` (polycor)、`pbvnorm`、`factanal`、`omega` (McDonald の ω。psych) |
|
|
239
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)` など) |
|
|
@@ -316,7 +317,7 @@ minify 済みの ES モジュール、gzip で 322 KB) を jsDelivr から読み
|
|
|
316
317
|
|
|
317
318
|
```html
|
|
318
319
|
<script type="module">
|
|
319
|
-
import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.
|
|
320
|
+
import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.13.0/dist/rstats.js";
|
|
320
321
|
console.log(pnorm(1.96)); // ≈ 0.9750021049
|
|
321
322
|
</script>
|
|
322
323
|
```
|
|
@@ -330,13 +331,13 @@ minify 済みの ES モジュール、gzip で 322 KB) を jsDelivr から読み
|
|
|
330
331
|
|
|
331
332
|
一部の分野だけを使うページでは、代わりに分野ごとのバンドルを読み込めます。`dist/distributions.js`、
|
|
332
333
|
`dist/tests.js`、`dist/linalg.js`、`dist/descriptive.js`、`dist/numerics.js`、`dist/special.js`、
|
|
333
|
-
`dist/mixed.js`、`dist/regression.js`、`dist/multivariate.js`、`dist/timeseries.js` は上のサブパスと同じ関数を export し、共通のコードを `dist/chunks/` で共有します。そのため、
|
|
334
|
+
`dist/mixed.js`、`dist/regression.js`、`dist/multivariate.js`、`dist/timeseries.js`、`dist/causal.js` は上のサブパスと同じ関数を export し、共通のコードを `dist/chunks/` で共有します。そのため、
|
|
334
335
|
2 つの分野を読み込んでも共通部分は 1 回しか読み込まれません。chunk を含めた 1 分野の転送量は、gzip で
|
|
335
336
|
39 KB (`special`) から 288 KB (`tests`) です。
|
|
336
337
|
|
|
337
338
|
1 つのページでは、`dist/rstats.js` か分野ごとのバンドルのどちらか一方だけを使ってください。両者は別々の
|
|
338
339
|
モジュールの集まりなので、混ぜると共通のコードが 2 回読み込まれ、乱数の状態も 2 つになります (一方の `setSeed`
|
|
339
|
-
は他方の乱数に効きません)。`dist/rstats.js` と `dist/mixed.js`・`dist/regression.js`・`dist/multivariate.js`・`dist/timeseries.js` を一緒に読み込む場合も、
|
|
340
|
+
は他方の乱数に効きません)。`dist/rstats.js` と `dist/mixed.js`・`dist/regression.js`・`dist/multivariate.js`・`dist/timeseries.js`・`dist/causal.js` を一緒に読み込む場合も、
|
|
340
341
|
これらは共通のコードを別に持ち込みます。
|
|
341
342
|
|
|
342
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.
|
|
17
|
+
Status: **1.13.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,13 +217,14 @@ 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`), `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` |
|
|
220
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` |
|
|
221
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`) |
|
|
222
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`) |
|
|
223
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) |
|
|
224
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) |
|
|
225
226
|
| Meta-analysis | `escalc` (effect sizes and sampling variances), `rma` (equal- and random-effects meta-analysis and meta-regression), `confintRma`, `predictRma`, `regtest` (metafor) |
|
|
226
|
-
| 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) |
|
|
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) |
|
|
227
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` |
|
|
228
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` |
|
|
229
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,7 +232,7 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
|
|
|
231
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) |
|
|
232
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) |
|
|
233
234
|
| Multiple comparisons | `dscfAllPairsTest` (Steel-Dwass), `kwAllPairsDunnTest`, `kwManyOneDunnTest`, `manyOneUTest` (Steel's many-one rank test), `dunnettTest`, `gamesHowellTest`, `tukeyTest` (PMCMRplus), `dunnTest` (dunn.test), `glhtDunnett` (multcomp) |
|
|
234
|
-
| 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 (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) |
|
|
235
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) |
|
|
236
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) |
|
|
237
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)`, ...) |
|
|
@@ -315,7 +316,7 @@ function except those of `/mixed` and `/regression`, 322 KB gzipped) from jsDeli
|
|
|
315
316
|
|
|
316
317
|
```html
|
|
317
318
|
<script type="module">
|
|
318
|
-
import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.
|
|
319
|
+
import { pnorm } from "https://cdn.jsdelivr.net/npm/@numero-uno-jpn/rstats@1.13.0/dist/rstats.js";
|
|
319
320
|
console.log(pnorm(1.96)); // ≈ 0.9750021049
|
|
320
321
|
</script>
|
|
321
322
|
```
|
|
@@ -329,13 +330,13 @@ browser console, assign `window.rs = rs` yourself.
|
|
|
329
330
|
|
|
330
331
|
A page that needs only some areas can load the per-area bundles instead: `dist/distributions.js`,
|
|
331
332
|
`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` and `dist/
|
|
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
|
|
333
334
|
`dist/chunks/`, so loading two areas does not load that code twice. With its chunks, one area
|
|
334
335
|
transfers 39 KB (`special`) to 288 KB (`tests`) gzipped.
|
|
335
336
|
|
|
336
337
|
Use either `dist/rstats.js` or the per-area bundles on one page, not both: they are separate sets of modules, so a
|
|
337
338
|
page that mixes them loads the common code twice and has two random number states (`setSeed` from one does not seed
|
|
338
|
-
the generators of the other). The same holds for `dist/rstats.js` with `dist/mixed.js`, `dist/regression.js`, `dist/multivariate.js` or `dist/
|
|
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
|
|
339
340
|
of the common code.
|
|
340
341
|
|
|
341
342
|
Other npm-based CDNs work as well, for example `https://esm.sh/@numero-uno-jpn/rstats`. Release tags also contain
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { MatchResult } from "./match.js";
|
|
2
|
+
import type { WeightitEstimand, WeightitResult } from "./weightit.js";
|
|
3
|
+
/**
|
|
4
|
+
* The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
|
|
5
|
+
* weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
|
|
6
|
+
* @category Causal inference
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* matchWeights(match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3])); // [1, 1, 1, 1, 0]
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function matchWeights(m: MatchResult): number[];
|
|
13
|
+
/** Options of {@link balTab}. Equivalent to the arguments of cobalt's `bal.tab()` for a `Match` or `weightit` object.
|
|
14
|
+
* @category Causal inference
|
|
15
|
+
*/
|
|
16
|
+
export interface BalTabOptions {
|
|
17
|
+
/**
|
|
18
|
+
* The result of {@link match}: gives the weights ({@link matchWeights}), the estimand and, with a caliper, the
|
|
19
|
+
* discarded units. Alternative to `weights` and `estimand`.
|
|
20
|
+
*/
|
|
21
|
+
match?: MatchResult;
|
|
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. */
|
|
28
|
+
weights?: readonly number[];
|
|
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[]>>;
|
|
33
|
+
/** Binary covariates: `"raw"` difference in proportions (default, as cobalt) or `"std"` standardised. */
|
|
34
|
+
binary?: "raw" | "std";
|
|
35
|
+
}
|
|
36
|
+
/** Result of {@link balTab}: one entry per covariate, in the order given (cobalt's `Balance` table), and the counts.
|
|
37
|
+
* @category Causal inference
|
|
38
|
+
*/
|
|
39
|
+
export interface BalTabResult {
|
|
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). */
|
|
42
|
+
rows: string[];
|
|
43
|
+
/** `"Distance"` (the propensity score), `"Contin."` or `"Binary"` (two distinct values, 0 and 1). */
|
|
44
|
+
type: ("Distance" | "Contin." | "Binary")[];
|
|
45
|
+
/** Difference treated − control before matching: standardised (continuous, or binary with `binary: "std"`) or raw. */
|
|
46
|
+
diffUn: number[];
|
|
47
|
+
/** The same after matching (weighted); NaN without weights. */
|
|
48
|
+
diffAdj: number[];
|
|
49
|
+
/** Variance ratio treated / control before matching (NaN for binary covariates). */
|
|
50
|
+
vRatioUn: number[];
|
|
51
|
+
/** The same after matching, with weighted variances; NaN for binary covariates or without weights. */
|
|
52
|
+
vRatioAdj: number[];
|
|
53
|
+
/**
|
|
54
|
+
* Sample sizes of the control and treated groups (cobalt's `Observations`): all (effective sample size, the same as
|
|
55
|
+
* the count), all (unweighted), matched (effective sample size `(sum w)^2 / sum w^2`), matched (unweighted:
|
|
56
|
+
* `w > 0`), unmatched (`w = 0`) and, when `match` has a caliper, discarded (its `indexDropped`, not counted as unmatched). The
|
|
57
|
+
* matched rows are NaN without weights. For a weightit result: unadjusted (the count)
|
|
58
|
+
* and adjusted (the effective sample size).
|
|
59
|
+
*/
|
|
60
|
+
observations: {
|
|
61
|
+
/** Row names, in the order of the counts. */
|
|
62
|
+
rows: string[];
|
|
63
|
+
/** Counts of the control group. */
|
|
64
|
+
control: number[];
|
|
65
|
+
/** Counts of the treated group. */
|
|
66
|
+
treated: number[];
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
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`.
|
|
74
|
+
*
|
|
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.
|
|
81
|
+
* @category Causal inference
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* const tr = [1, 0, 1, 0, 0, 1, 0, 0];
|
|
85
|
+
* const age = [52, 40, 61, 58, 33, 47, 50, 45];
|
|
86
|
+
* const m = match(tr, [0.4, -0.9, 1.2, 1.0, -1.5, 0.1, 0.3, -0.2]);
|
|
87
|
+
* const b = balTab(tr, { age }, { match: m });
|
|
88
|
+
* b.diffUn; // [1.1464120051932525]
|
|
89
|
+
* b.diffAdj; // [0.32888869001445803]
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
export declare function balTab(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, readonly number[] | readonly string[]>>, options?: BalTabOptions): BalTabResult;
|
|
93
|
+
/** Options of {@link tableOneSmd}.
|
|
94
|
+
* @category Causal inference
|
|
95
|
+
*/
|
|
96
|
+
export interface TableOneSmdOptions {
|
|
97
|
+
/** Treat `x` as categorical (tableone's `factorVars`): numbers or strings as levels. Default false. */
|
|
98
|
+
factor?: boolean;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Standardised mean difference of one variable between two groups. Equivalent to `tableone::ExtractSmd()` in R. The
|
|
102
|
+
* call followed is `ExtractSmd(CreateTableOne(vars, strata, data, factorVars))` with two groups. Missing values (`NaN`,
|
|
103
|
+
* `null`) are left out.
|
|
104
|
+
*
|
|
105
|
+
* Numeric: `|mean1 − mean0| / sqrt((s1² + s0²) / 2)` with the groups' SDs (divisor `n − 1`). Categorical
|
|
106
|
+
* (`factor: true`): Yang and Dalton's `sqrt(d' S⁻¹ d)`, `d` the differences of the proportions of the levels after the
|
|
107
|
+
* first, `S` the mean of the two groups' multinomial covariance matrices `p_k (δ_kl − p_l)`; with two levels
|
|
108
|
+
* `|p1 − p0| / sqrt((p1(1 − p1) + p0(1 − p0)) / 2)`. 0 when both the difference and the spread are 0. When `S` is
|
|
109
|
+
* singular (a level in one group only) the generalised inverse is used, as tableone; when `S` is 0 (one level in each
|
|
110
|
+
* group) the result is NaN, as tableone.
|
|
111
|
+
* @category Causal inference
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* tableOneSmd([1, 2, 3, 2, 5, 4], [0, 0, 0, 1, 1, 1]); // 1.2909944487358056
|
|
115
|
+
* tableOneSmd(["a", "b", "a", "b", "b", "b"], [0, 0, 0, 1, 1, 1], { factor: true }); // 2
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export declare function tableOneSmd(x: readonly (number | string | null)[], group: readonly (number | string | boolean)[], options?: TableOneSmdOptions): number;
|
|
@@ -0,0 +1,264 @@
|
|
|
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 { compareCodePoints } from "../models/modelFrame.js";
|
|
8
|
+
import { rescaled } from "./scale.js";
|
|
9
|
+
import { ldexp } from "../internal/summary.js";
|
|
10
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
11
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
12
|
+
const BAL_TAB_KEYS = ["match", "weightit", "weights", "estimand", "levels", "binary"];
|
|
13
|
+
const TABLE_ONE_SMD_KEYS = ["factor"];
|
|
14
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
15
|
+
/**
|
|
16
|
+
* The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
|
|
17
|
+
* weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
|
|
18
|
+
* @category Causal inference
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* matchWeights(match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3])); // [1, 1, 1, 1, 0]
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export function matchWeights(m) {
|
|
25
|
+
const w = new Array(m.nobs).fill(0);
|
|
26
|
+
m.indexTreated.forEach((t, i) => {
|
|
27
|
+
w[t - 1] += m.weights[i];
|
|
28
|
+
w[m.indexControl[i] - 1] += m.weights[i];
|
|
29
|
+
});
|
|
30
|
+
return w;
|
|
31
|
+
}
|
|
32
|
+
function isTreated(t, i) {
|
|
33
|
+
if (t === true || t === 1)
|
|
34
|
+
return true;
|
|
35
|
+
if (t === false || t === 0)
|
|
36
|
+
return false;
|
|
37
|
+
throw new RangeError(`'tr' must be 0 or 1 (element ${i + 1})`);
|
|
38
|
+
}
|
|
39
|
+
/** Weighted mean and variance (divisor sum(w) - sum(w^2) / sum(w), cobalt's), over the units with g === group. */
|
|
40
|
+
function moments(v, w, g, group) {
|
|
41
|
+
let sw = 0, sw2 = 0, swx = 0;
|
|
42
|
+
for (let i = 0; i < v.length; i++) {
|
|
43
|
+
if (g[i] !== group)
|
|
44
|
+
continue;
|
|
45
|
+
const wi = w === null ? 1 : w[i];
|
|
46
|
+
sw += wi;
|
|
47
|
+
sw2 += wi * wi;
|
|
48
|
+
swx += wi * v[i];
|
|
49
|
+
}
|
|
50
|
+
const mean = swx / sw;
|
|
51
|
+
let ss = 0;
|
|
52
|
+
for (let i = 0; i < v.length; i++) {
|
|
53
|
+
if (g[i] !== group)
|
|
54
|
+
continue;
|
|
55
|
+
const wi = w === null ? 1 : w[i];
|
|
56
|
+
ss += wi * (v[i] - mean) * (v[i] - mean);
|
|
57
|
+
}
|
|
58
|
+
return [mean, ss / (sw - sw2 / sw)];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
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`.
|
|
65
|
+
*
|
|
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.
|
|
72
|
+
* @category Causal inference
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* const tr = [1, 0, 1, 0, 0, 1, 0, 0];
|
|
76
|
+
* const age = [52, 40, 61, 58, 33, 47, 50, 45];
|
|
77
|
+
* const m = match(tr, [0.4, -0.9, 1.2, 1.0, -1.5, 0.1, 0.3, -0.2]);
|
|
78
|
+
* const b = balTab(tr, { age }, { match: m });
|
|
79
|
+
* b.diffUn; // [1.1464120051932525]
|
|
80
|
+
* b.diffAdj; // [0.32888869001445803]
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export function balTab(tr, covariates, options = {}) {
|
|
84
|
+
checkOptions(options, BAL_TAB_KEYS, "balTab"); // generated: option-keys.mjs
|
|
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";
|
|
90
|
+
const discarded = new Set(m?.indexDropped ?? []);
|
|
91
|
+
const withDiscarded = m !== undefined && m.caliper !== null;
|
|
92
|
+
const n = tr.length;
|
|
93
|
+
const g = tr.map(isTreated);
|
|
94
|
+
if (!g.includes(true) || !g.includes(false))
|
|
95
|
+
throw new RangeError("'tr' must contain both groups");
|
|
96
|
+
if (weights !== undefined && weights.length !== n)
|
|
97
|
+
throw new RangeError("'weights' must have the length of 'tr'");
|
|
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;
|
|
122
|
+
const result = {
|
|
123
|
+
rows: columns.map(([name]) => name), type: [], diffUn: [], diffAdj: [], vRatioUn: [], vRatioAdj: [],
|
|
124
|
+
observations: {
|
|
125
|
+
rows: adjustedRows ? ["Unadjusted", "Adjusted"]
|
|
126
|
+
: ["All (ESS)", "All (Unweighted)", "Matched (ESS)", "Matched (Unweighted)", "Unmatched", ...(withDiscarded ? ["Discarded"] : [])],
|
|
127
|
+
control: [], treated: [],
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
for (const [name, v, kind] of columns) {
|
|
131
|
+
if (v.some((x) => !Number.isFinite(x)))
|
|
132
|
+
throw new RangeError(`covariate '${name}' has missing or infinite values`);
|
|
133
|
+
const isBinary = kind === null && new Set(v).size <= 2 && v.every((x) => x === 0 || x === 1);
|
|
134
|
+
// a continuous covariate rescaled exactly: its standardised differences and variance ratios do not change
|
|
135
|
+
const r = isBinary ? null : rescaled(v);
|
|
136
|
+
const vs = r === null ? v : r.values;
|
|
137
|
+
const [m1, var1] = moments(vs, null, g, true);
|
|
138
|
+
const [m0, var0] = moments(vs, null, g, false);
|
|
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
|
+
}
|
|
157
|
+
const scale = isBinary && binary === "raw" ? 1 : s;
|
|
158
|
+
result.type.push(kind ?? (isBinary ? "Binary" : "Contin."));
|
|
159
|
+
// a difference of 0 is 0 (cobalt's, also for a constant covariate whose SD is 0)
|
|
160
|
+
result.diffUn.push(m1 === m0 ? 0 : (m1 - m0) / scale);
|
|
161
|
+
// a zero control variance gives NA in cobalt (not Inf)
|
|
162
|
+
result.vRatioUn.push(isBinary || var0 === 0 ? NaN : var1 / var0);
|
|
163
|
+
if (weights === undefined) {
|
|
164
|
+
result.diffAdj.push(NaN);
|
|
165
|
+
result.vRatioAdj.push(NaN);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const [a1, av1] = moments(vs, weights, g, true);
|
|
169
|
+
const [a0, av0] = moments(vs, weights, g, false);
|
|
170
|
+
result.diffAdj.push(a1 === a0 ? 0 : (a1 - a0) / scale);
|
|
171
|
+
result.vRatioAdj.push(isBinary || av0 === 0 ? NaN : av1 / av0);
|
|
172
|
+
}
|
|
173
|
+
for (const group of [false, true]) {
|
|
174
|
+
let count = 0, sw = 0, sw2 = 0, positive = 0, gone = 0;
|
|
175
|
+
for (let i = 0; i < n; i++) {
|
|
176
|
+
if (g[i] !== group)
|
|
177
|
+
continue;
|
|
178
|
+
count++;
|
|
179
|
+
if (discarded.has(i + 1))
|
|
180
|
+
gone++;
|
|
181
|
+
if (weights === undefined)
|
|
182
|
+
continue;
|
|
183
|
+
const wi = weights[i];
|
|
184
|
+
sw += wi;
|
|
185
|
+
sw2 += wi * wi;
|
|
186
|
+
if (wi > 0)
|
|
187
|
+
positive++;
|
|
188
|
+
}
|
|
189
|
+
const side = group ? result.observations.treated : result.observations.control;
|
|
190
|
+
if (adjustedRows) {
|
|
191
|
+
side.push(count, sw * sw / sw2);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const matched = weights === undefined ? [NaN, NaN, NaN] : [sw * sw / sw2, positive, count - positive - gone];
|
|
195
|
+
if (withDiscarded)
|
|
196
|
+
matched.push(gone);
|
|
197
|
+
side.push(count, count, ...matched);
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Standardised mean difference of one variable between two groups. Equivalent to `tableone::ExtractSmd()` in R. The
|
|
203
|
+
* call followed is `ExtractSmd(CreateTableOne(vars, strata, data, factorVars))` with two groups. Missing values (`NaN`,
|
|
204
|
+
* `null`) are left out.
|
|
205
|
+
*
|
|
206
|
+
* Numeric: `|mean1 − mean0| / sqrt((s1² + s0²) / 2)` with the groups' SDs (divisor `n − 1`). Categorical
|
|
207
|
+
* (`factor: true`): Yang and Dalton's `sqrt(d' S⁻¹ d)`, `d` the differences of the proportions of the levels after the
|
|
208
|
+
* first, `S` the mean of the two groups' multinomial covariance matrices `p_k (δ_kl − p_l)`; with two levels
|
|
209
|
+
* `|p1 − p0| / sqrt((p1(1 − p1) + p0(1 − p0)) / 2)`. 0 when both the difference and the spread are 0. When `S` is
|
|
210
|
+
* singular (a level in one group only) the generalised inverse is used, as tableone; when `S` is 0 (one level in each
|
|
211
|
+
* group) the result is NaN, as tableone.
|
|
212
|
+
* @category Causal inference
|
|
213
|
+
* @example
|
|
214
|
+
* ```ts
|
|
215
|
+
* tableOneSmd([1, 2, 3, 2, 5, 4], [0, 0, 0, 1, 1, 1]); // 1.2909944487358056
|
|
216
|
+
* tableOneSmd(["a", "b", "a", "b", "b", "b"], [0, 0, 0, 1, 1, 1], { factor: true }); // 2
|
|
217
|
+
* ```
|
|
218
|
+
*/
|
|
219
|
+
export function tableOneSmd(x, group, options = {}) {
|
|
220
|
+
checkOptions(options, TABLE_ONE_SMD_KEYS, "tableOneSmd"); // generated: option-keys.mjs
|
|
221
|
+
const { factor = false } = options;
|
|
222
|
+
if (x.length !== group.length)
|
|
223
|
+
throw new RangeError("'x' and 'group' must have the same length");
|
|
224
|
+
const glev = [...new Set(group)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
225
|
+
if (glev.length !== 2)
|
|
226
|
+
throw new RangeError("'group' must have exactly two levels");
|
|
227
|
+
const keep = (v) => v !== null && !(typeof v === "number" && Number.isNaN(v));
|
|
228
|
+
const parts = glev.map((lv) => x.filter((v, i) => group[i] === lv && keep(v)));
|
|
229
|
+
if (!factor) {
|
|
230
|
+
if (parts.flat().some((e) => typeof e !== "number"))
|
|
231
|
+
throw new TypeError("'x' must be numeric unless factor: true");
|
|
232
|
+
// rescaled exactly as one column (the SMD does not change)
|
|
233
|
+
const all = rescaled(parts.flat()).values;
|
|
234
|
+
const split = [all.slice(0, parts[0].length), all.slice(parts[0].length)];
|
|
235
|
+
const stats = split.map((v) => {
|
|
236
|
+
const mean = v.reduce((s, e) => s + e, 0) / v.length;
|
|
237
|
+
return [mean, v.reduce((s, e) => s + (e - mean) * (e - mean), 0) / (v.length - 1)];
|
|
238
|
+
});
|
|
239
|
+
const diff = stats[1][0] - stats[0][0];
|
|
240
|
+
const sd = Math.sqrt((stats[0][1] + stats[1][1]) / 2);
|
|
241
|
+
return diff === 0 ? 0 : Math.abs(diff) / sd;
|
|
242
|
+
}
|
|
243
|
+
const levels = [...new Set(parts.flat())].sort((a, b) => (typeof a === "number" && typeof b === "number" ? a - b
|
|
244
|
+
: String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0));
|
|
245
|
+
const props = parts.map((p) => levels.slice(1).map((lv) => p.filter((e) => e === lv).length / p.length));
|
|
246
|
+
const d = props[1].map((q, k) => q - props[0][k]);
|
|
247
|
+
if (d.every((e) => e === 0))
|
|
248
|
+
return 0;
|
|
249
|
+
const K = d.length;
|
|
250
|
+
const S = Array.from({ length: K }, (_, k) => Array.from({ length: K }, (_, l) => {
|
|
251
|
+
const c = (p) => (k === l ? p[k] * (1 - p[k]) : -p[k] * p[l]);
|
|
252
|
+
return (c(props[0]) + c(props[1])) / 2;
|
|
253
|
+
}));
|
|
254
|
+
// S is singular when a level is in one group only: tableone's value is then that of the generalised inverse
|
|
255
|
+
// (MASS::ginv's; experiments/psm112-edge.json factorAbsent), and NaN when S is 0 (each group has one level)
|
|
256
|
+
if (S.every((row) => row.every((v) => v === 0)))
|
|
257
|
+
return NaN;
|
|
258
|
+
const Si = ginv(S);
|
|
259
|
+
let q = 0;
|
|
260
|
+
for (let k = 0; k < K; k++)
|
|
261
|
+
for (let l = 0; l < K; l++)
|
|
262
|
+
q += d[k] * Si[k][l] * d[l];
|
|
263
|
+
return Math.sqrt(q);
|
|
264
|
+
}
|