@numero-uno-jpn/rstats 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.ja.md +6 -5
- package/README.md +6 -5
- package/dist/causal/balance.d.ts +106 -0
- package/dist/causal/balance.js +216 -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.js +2 -0
- package/dist/chunks/{chunk-IRO6MXW2.js → chunk-2P42OXYW.js} +2 -2
- package/dist/chunks/{chunk-M4SLTLOX.js → chunk-3QOW56EJ.js} +2 -2
- package/dist/chunks/{chunk-XLBSUUWY.js → chunk-3QSYPBUM.js} +2 -2
- package/dist/chunks/{chunk-46DELNLN.js → chunk-4B7NEJCE.js} +2 -2
- package/dist/chunks/{chunk-OG5FTIWF.js → chunk-4GRV66HW.js} +2 -2
- package/dist/chunks/{chunk-HIPKYBZ3.js → chunk-4U65I4J2.js} +2 -2
- package/dist/chunks/{chunk-MJLK2RIQ.js → chunk-52KGBGFL.js} +1 -1
- package/dist/chunks/{chunk-JFZOKMZA.js → chunk-5AR4V7MW.js} +2 -2
- package/dist/chunks/{chunk-YPDFCKL4.js → chunk-7FXBOYIH.js} +2 -2
- package/dist/chunks/{chunk-NO675KX4.js → chunk-7K2LMKZR.js} +2 -2
- package/dist/chunks/chunk-7UI4PW32.js +2 -0
- package/dist/chunks/{chunk-BNHMQU7V.js → chunk-CHKBDZC4.js} +2 -2
- package/dist/chunks/{chunk-W2D6IDBY.js → chunk-CKBUE4FV.js} +2 -2
- package/dist/chunks/{chunk-SV6SLUVB.js → chunk-CMTCPLIA.js} +2 -2
- package/dist/chunks/chunk-DWVTVOQS.js +2 -0
- package/dist/chunks/{chunk-QY4OBLXK.js → chunk-FFMMKXMK.js} +2 -2
- package/dist/chunks/{chunk-EV7ZQC6D.js → chunk-HF3QOIZX.js} +2 -2
- package/dist/chunks/chunk-JG26HC2H.js +2 -0
- package/dist/chunks/{chunk-KICTA3JY.js → chunk-L54WIMTZ.js} +2 -2
- package/dist/chunks/{chunk-TNU4SMV3.js → chunk-MAFZ5FGL.js} +2 -2
- package/dist/chunks/{chunk-Y2SS3GX2.js → chunk-MJ7IY7AF.js} +2 -2
- package/dist/chunks/chunk-MUYGPZ37.js +3 -0
- package/dist/chunks/{chunk-PF6LEBKO.js → chunk-NAACMR7H.js} +2 -2
- package/dist/chunks/{chunk-OWOBNS75.js → chunk-NGDBJR3K.js} +2 -2
- package/dist/chunks/{chunk-P23KCD67.js → chunk-NQT7ZWL6.js} +2 -2
- package/dist/chunks/{chunk-ZW5OCUIY.js → chunk-O6OMXX5U.js} +1 -1
- package/dist/chunks/{chunk-JWMVP7XO.js → chunk-PYFASERO.js} +2 -2
- package/dist/chunks/{chunk-W27XXELU.js → chunk-QT32BMYA.js} +2 -2
- package/dist/chunks/{chunk-DMT423BG.js → chunk-SKQHW2GD.js} +2 -2
- package/dist/chunks/{chunk-JD6JHIVV.js → chunk-SLMS3FQD.js} +1 -1
- package/dist/chunks/{chunk-BA32XHDA.js → chunk-SZR5HAMB.js} +2 -2
- package/dist/chunks/{chunk-QRUQEJJ5.js → chunk-T5TE5KCP.js} +2 -2
- package/dist/chunks/{chunk-BZBPPRSH.js → chunk-ULQXNAI6.js} +2 -2
- package/dist/chunks/{chunk-3K5KP3M2.js → chunk-UPFMYDF7.js} +2 -2
- package/dist/chunks/{chunk-WHKUEZQI.js → chunk-WACTNIKS.js} +2 -2
- package/dist/chunks/{chunk-BGY7Y3P4.js → chunk-WSDLT4AR.js} +1 -1
- package/dist/chunks/{chunk-HCHZ6M34.js → chunk-WUNTM7PJ.js} +2 -2
- package/dist/chunks/chunk-XQSYV3IZ.js +2 -0
- package/dist/chunks/{chunk-BKH5GQNA.js → chunk-YKCZF4ES.js} +2 -2
- package/dist/chunks/{chunk-XKQSKVCL.js → chunk-ZHAT6244.js} +2 -2
- package/dist/chunks/{chunk-S5JZMHAW.js → chunk-ZK7FW5UX.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/causal.d.ts +2 -0
- package/dist/entries/causal.js +3 -0
- package/dist/entries/tests.d.ts +1 -0
- package/dist/entries/tests.js +1 -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/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-6VIOWV53.js +0 -2
- package/dist/chunks/chunk-HPWRADJM.js +0 -2
- package/dist/chunks/chunk-Z6UI6ON2.js +0 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,14 @@ While the version is 0.x, a minor release (0.y.0) may contain breaking changes;
|
|
|
7
7
|
they are listed under **Breaking** for each release. From 1.0.0 the project follows
|
|
8
8
|
[Semantic Versioning](https://semver.org/).
|
|
9
9
|
|
|
10
|
+
## 1.12.0 - 2026-11-24
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Causal inference** in the separate `/causal` area: propensity score matching (`match`, after `Matching::Match` with `ties = FALSE` and `replace = FALSE`: ATT, ATE and ATC, 1:M, caliper), matching weights (`matchWeights`), covariate balance before and after (`balTab`, after `cobalt::bal.tab`) and tableone's standardized mean difference (`tableOneSmd`).
|
|
15
|
+
- **Conditional logistic regression** (`clogit`, after `survival::clogit`): the exact conditional likelihood and the approximate (Breslow) one.
|
|
16
|
+
- Ties among three or more matching candidates are broken by rStats.js's own rule; without ties, and with two tied candidates, the pairs and the random numbers are R's ([the differences](docs/differences-from-r.md#propensity-score-matching-and-conditional-logistic-regression-1120)).
|
|
17
|
+
|
|
10
18
|
## 1.11.0 - 2026-11-24
|
|
11
19
|
|
|
12
20
|
### 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.12.0。** R の stats パッケージの数値計算の中心
|
|
20
20
|
(分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
|
|
21
21
|
[ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
|
|
22
22
|
|
|
@@ -219,6 +219,7 @@ 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
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`) |
|
|
@@ -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 の累積ハザード、重み、ロバスト標準誤差、信頼区間、中央値、制限平均、計数過程データ)、`rmst2` (非調整・共変量調整の制限平均生存時間と制限平均損失時間)、`coxph` (Cox 回帰。Efron と Breslow のタイ、ケース重み、層、Wald・尤度比・スコア検定、計数過程データ、ロバスト分散と `cluster`)、`coxZph` (比例ハザード性の検定)、`cuminc`・`timepoints` (累積発生率と Gray の検定)、`crr`・`predictCrr` (Fine-Gray 回帰と予測)、`survreg`・`survregPredict`・`survregResiduals` (パラメトリックな加速故障時間回帰) |
|
|
237
|
+
| 生存時間解析 | `survdiff` (log-rank と G-rho 族)、`survfit` (Kaplan-Meier と Nelson-Aalen・Fleming-Harrington の累積ハザード、重み、ロバスト標準誤差、信頼区間、中央値、制限平均、計数過程データ)、`rmst2` (非調整・共変量調整の制限平均生存時間と制限平均損失時間)、`coxph` (Cox 回帰。Efron と Breslow のタイ、ケース重み、層、Wald・尤度比・スコア検定、計数過程データ、ロバスト分散と `cluster`)、`clogit` (マッチした組の条件付きロジスティック回帰: 正確な尤度と近似の尤度)、`coxZph` (比例ハザード性の検定)、`cuminc`・`timepoints` (累積発生率と Gray の検定)、`crr`・`predictCrr` (Fine-Gray 回帰と予測)、`survreg`・`survregPredict`・`survregResiduals` (パラメトリックな加速故障時間回帰) |
|
|
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.12.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.12.0.** The goal is to cover the numerical core of R's
|
|
18
18
|
`stats` package (distributions, descriptive statistics, hypothesis tests, linear models, special
|
|
19
19
|
functions, numerical methods and the basics of linear algebra) with R-compatible results; see [ROADMAP.md](ROADMAP.md) for what remains. See [CHANGELOG.md](CHANGELOG.md).
|
|
20
20
|
|
|
@@ -217,6 +217,7 @@ 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
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`) |
|
|
@@ -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, 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
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.12.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,106 @@
|
|
|
1
|
+
import type { MatchEstimand, MatchResult } from "./match.js";
|
|
2
|
+
/**
|
|
3
|
+
* The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
|
|
4
|
+
* weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
|
|
5
|
+
* @category Causal inference
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* matchWeights(match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3])); // [1, 1, 1, 1, 0]
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export declare function matchWeights(m: MatchResult): number[];
|
|
12
|
+
/** Options of {@link balTab}. Equivalent to the arguments of cobalt's `bal.tab()` for a `Match` object.
|
|
13
|
+
* @category Causal inference
|
|
14
|
+
*/
|
|
15
|
+
export interface BalTabOptions {
|
|
16
|
+
/**
|
|
17
|
+
* The result of {@link match}: gives the weights ({@link matchWeights}), the estimand and, with a caliper, the
|
|
18
|
+
* discarded units. Alternative to `weights` and `estimand`.
|
|
19
|
+
*/
|
|
20
|
+
match?: MatchResult;
|
|
21
|
+
/** The weights after matching (from {@link matchWeights}); without them only the unadjusted columns are filled. */
|
|
22
|
+
weights?: readonly number[];
|
|
23
|
+
/** The estimand, which chooses the SD of the denominator (default `"ATT"`). */
|
|
24
|
+
estimand?: MatchEstimand;
|
|
25
|
+
/** Binary covariates: `"raw"` difference in proportions (default, as cobalt) or `"std"` standardised. */
|
|
26
|
+
binary?: "raw" | "std";
|
|
27
|
+
}
|
|
28
|
+
/** Result of {@link balTab}: one entry per covariate, in the order given (cobalt's `Balance` table), and the counts.
|
|
29
|
+
* @category Causal inference
|
|
30
|
+
*/
|
|
31
|
+
export interface BalTabResult {
|
|
32
|
+
/** Covariate names. */
|
|
33
|
+
rows: string[];
|
|
34
|
+
/** `"Contin."` or `"Binary"` (a covariate with two distinct values, 0 and 1). */
|
|
35
|
+
type: ("Contin." | "Binary")[];
|
|
36
|
+
/** Difference treated − control before matching: standardised (continuous, or binary with `binary: "std"`) or raw. */
|
|
37
|
+
diffUn: number[];
|
|
38
|
+
/** The same after matching (weighted); NaN without weights. */
|
|
39
|
+
diffAdj: number[];
|
|
40
|
+
/** Variance ratio treated / control before matching (NaN for binary covariates). */
|
|
41
|
+
vRatioUn: number[];
|
|
42
|
+
/** The same after matching, with weighted variances; NaN for binary covariates or without weights. */
|
|
43
|
+
vRatioAdj: number[];
|
|
44
|
+
/**
|
|
45
|
+
* Sample sizes of the control and treated groups (cobalt's `Observations`): all (effective sample size, the same as
|
|
46
|
+
* the count), all (unweighted), matched (effective sample size `(sum w)^2 / sum w^2`), matched (unweighted:
|
|
47
|
+
* `w > 0`), unmatched (`w = 0`) and, when `match` has a caliper, discarded (its `indexDropped`, not counted as unmatched). The
|
|
48
|
+
* matched rows are NaN without weights.
|
|
49
|
+
*/
|
|
50
|
+
observations: {
|
|
51
|
+
/** Row names, in the order of the counts. */
|
|
52
|
+
rows: string[];
|
|
53
|
+
/** Counts of the control group. */
|
|
54
|
+
control: number[];
|
|
55
|
+
/** Counts of the treated group. */
|
|
56
|
+
treated: number[];
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Covariate balance of two groups before and after matching: standardised mean differences and variance ratios.
|
|
61
|
+
* Equivalent to `cobalt::bal.tab()` in R. The call followed is
|
|
62
|
+
* `bal.tab(m, formula = tr ~ ..., data, un = TRUE, disp.v.ratio = TRUE, binary)` for a `Match` object `m`.
|
|
63
|
+
*
|
|
64
|
+
* The difference is `(mean treated − mean control) / s`, with means weighted after matching. The SD `s` is always that
|
|
65
|
+
* of the unmatched sample: of the treated for ATT, of the controls for ATC, `sqrt((s1² + s0²) / 2)` for ATE; for a
|
|
66
|
+
* binary covariate (with `binary: "std"`) `sqrt(p(1 − p))` in place of the SD (the mean of `p1(1 − p1)` and
|
|
67
|
+
* `p0(1 − p0)` for ATE).
|
|
68
|
+
* Variance ratios are treated / control. Factor covariates are not split: give one 0/1 column per level.
|
|
69
|
+
* @category Causal inference
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* const tr = [1, 0, 1, 0, 0, 1, 0, 0];
|
|
73
|
+
* const age = [52, 40, 61, 58, 33, 47, 50, 45];
|
|
74
|
+
* const m = match(tr, [0.4, -0.9, 1.2, 1.0, -1.5, 0.1, 0.3, -0.2]);
|
|
75
|
+
* const b = balTab(tr, { age }, { match: m });
|
|
76
|
+
* b.diffUn; // [1.1464120051932525]
|
|
77
|
+
* b.diffAdj; // [0.32888869001445803]
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export declare function balTab(tr: readonly (number | boolean)[], covariates: Readonly<Record<string, readonly number[]>>, options?: BalTabOptions): BalTabResult;
|
|
81
|
+
/** Options of {@link tableOneSmd}.
|
|
82
|
+
* @category Causal inference
|
|
83
|
+
*/
|
|
84
|
+
export interface TableOneSmdOptions {
|
|
85
|
+
/** Treat `x` as categorical (tableone's `factorVars`): numbers or strings as levels. Default false. */
|
|
86
|
+
factor?: boolean;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Standardised mean difference of one variable between two groups. Equivalent to `tableone::ExtractSmd()` in R. The
|
|
90
|
+
* call followed is `ExtractSmd(CreateTableOne(vars, strata, data, factorVars))` with two groups. Missing values (`NaN`,
|
|
91
|
+
* `null`) are left out.
|
|
92
|
+
*
|
|
93
|
+
* Numeric: `|mean1 − mean0| / sqrt((s1² + s0²) / 2)` with the groups' SDs (divisor `n − 1`). Categorical
|
|
94
|
+
* (`factor: true`): Yang and Dalton's `sqrt(d' S⁻¹ d)`, `d` the differences of the proportions of the levels after the
|
|
95
|
+
* first, `S` the mean of the two groups' multinomial covariance matrices `p_k (δ_kl − p_l)`; with two levels
|
|
96
|
+
* `|p1 − p0| / sqrt((p1(1 − p1) + p0(1 − p0)) / 2)`. 0 when both the difference and the spread are 0. When `S` is
|
|
97
|
+
* singular (a level in one group only) the generalised inverse is used, as tableone; when `S` is 0 (one level in each
|
|
98
|
+
* group) the result is NaN, as tableone.
|
|
99
|
+
* @category Causal inference
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* tableOneSmd([1, 2, 3, 2, 5, 4], [0, 0, 0, 1, 1, 1]); // 1.2909944487358056
|
|
103
|
+
* tableOneSmd(["a", "b", "a", "b", "b", "b"], [0, 0, 0, 1, 1, 1], { factor: true }); // 2
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
export declare function tableOneSmd(x: readonly (number | string | null)[], group: readonly (number | string | boolean)[], options?: TableOneSmdOptions): number;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Covariate balance before and after matching: the standardised mean differences and variance ratios of cobalt's
|
|
2
|
+
// bal.tab (for a Match object) and the standardised mean differences of tableone's CreateTableOne / ExtractSmd. The
|
|
3
|
+
// definitions are in oracle/match-behaviour.md, from the packages' documentation and published output; Yang & Dalton
|
|
4
|
+
// (2012), "A unified approach to measuring the effect size between two groups using SAS", SAS Global Forum 335, for
|
|
5
|
+
// the categorical SMD. Written for rStats.js (no ported code).
|
|
6
|
+
import { ginv } from "../linalg/kappa.js";
|
|
7
|
+
import { rescaled } from "./scale.js";
|
|
8
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
9
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
10
|
+
const BAL_TAB_KEYS = ["match", "weights", "estimand", "binary"];
|
|
11
|
+
const TABLE_ONE_SMD_KEYS = ["factor"];
|
|
12
|
+
// Generated by `node scripts/option-keys.mjs --write` (end)
|
|
13
|
+
/**
|
|
14
|
+
* The weight of each unit after matching: every pair adds its weight `1 / M` to both of its units; unmatched units
|
|
15
|
+
* weigh 0. Equivalent to `cobalt::get.w()` in R. The call followed is `get.w(m)` for a `Match` object `m`.
|
|
16
|
+
* @category Causal inference
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* matchWeights(match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3])); // [1, 1, 1, 1, 0]
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export function matchWeights(m) {
|
|
23
|
+
const w = new Array(m.nobs).fill(0);
|
|
24
|
+
m.indexTreated.forEach((t, i) => {
|
|
25
|
+
w[t - 1] += m.weights[i];
|
|
26
|
+
w[m.indexControl[i] - 1] += m.weights[i];
|
|
27
|
+
});
|
|
28
|
+
return w;
|
|
29
|
+
}
|
|
30
|
+
function isTreated(t, i) {
|
|
31
|
+
if (t === true || t === 1)
|
|
32
|
+
return true;
|
|
33
|
+
if (t === false || t === 0)
|
|
34
|
+
return false;
|
|
35
|
+
throw new RangeError(`'tr' must be 0 or 1 (element ${i + 1})`);
|
|
36
|
+
}
|
|
37
|
+
/** Weighted mean and variance (divisor sum(w) - sum(w^2) / sum(w), cobalt's), over the units with g === group. */
|
|
38
|
+
function moments(v, w, g, group) {
|
|
39
|
+
let sw = 0, sw2 = 0, swx = 0;
|
|
40
|
+
for (let i = 0; i < v.length; i++) {
|
|
41
|
+
if (g[i] !== group)
|
|
42
|
+
continue;
|
|
43
|
+
const wi = w === null ? 1 : w[i];
|
|
44
|
+
sw += wi;
|
|
45
|
+
sw2 += wi * wi;
|
|
46
|
+
swx += wi * v[i];
|
|
47
|
+
}
|
|
48
|
+
const mean = swx / sw;
|
|
49
|
+
let ss = 0;
|
|
50
|
+
for (let i = 0; i < v.length; i++) {
|
|
51
|
+
if (g[i] !== group)
|
|
52
|
+
continue;
|
|
53
|
+
const wi = w === null ? 1 : w[i];
|
|
54
|
+
ss += wi * (v[i] - mean) * (v[i] - mean);
|
|
55
|
+
}
|
|
56
|
+
return [mean, ss / (sw - sw2 / sw)];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Covariate balance of two groups before and after matching: standardised mean differences and variance ratios.
|
|
60
|
+
* Equivalent to `cobalt::bal.tab()` in R. The call followed is
|
|
61
|
+
* `bal.tab(m, formula = tr ~ ..., data, un = TRUE, disp.v.ratio = TRUE, binary)` for a `Match` object `m`.
|
|
62
|
+
*
|
|
63
|
+
* The difference is `(mean treated − mean control) / s`, with means weighted after matching. The SD `s` is always that
|
|
64
|
+
* of the unmatched sample: of the treated for ATT, of the controls for ATC, `sqrt((s1² + s0²) / 2)` for ATE; for a
|
|
65
|
+
* binary covariate (with `binary: "std"`) `sqrt(p(1 − p))` in place of the SD (the mean of `p1(1 − p1)` and
|
|
66
|
+
* `p0(1 − p0)` for ATE).
|
|
67
|
+
* Variance ratios are treated / control. Factor covariates are not split: give one 0/1 column per level.
|
|
68
|
+
* @category Causal inference
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* const tr = [1, 0, 1, 0, 0, 1, 0, 0];
|
|
72
|
+
* const age = [52, 40, 61, 58, 33, 47, 50, 45];
|
|
73
|
+
* const m = match(tr, [0.4, -0.9, 1.2, 1.0, -1.5, 0.1, 0.3, -0.2]);
|
|
74
|
+
* const b = balTab(tr, { age }, { match: m });
|
|
75
|
+
* b.diffUn; // [1.1464120051932525]
|
|
76
|
+
* b.diffAdj; // [0.32888869001445803]
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export function balTab(tr, covariates, options = {}) {
|
|
80
|
+
checkOptions(options, BAL_TAB_KEYS, "balTab"); // generated: option-keys.mjs
|
|
81
|
+
const { match: m, binary = "raw" } = options;
|
|
82
|
+
const weights = m === undefined ? options.weights : matchWeights(m);
|
|
83
|
+
const estimand = m?.estimand ?? options.estimand ?? "ATT";
|
|
84
|
+
const discarded = new Set(m?.indexDropped ?? []);
|
|
85
|
+
const withDiscarded = m !== undefined && m.caliper !== null;
|
|
86
|
+
const n = tr.length;
|
|
87
|
+
const g = tr.map(isTreated);
|
|
88
|
+
if (!g.includes(true) || !g.includes(false))
|
|
89
|
+
throw new RangeError("'tr' must contain both groups");
|
|
90
|
+
if (weights !== undefined && weights.length !== n)
|
|
91
|
+
throw new RangeError("'weights' must have the length of 'tr'");
|
|
92
|
+
const rows = Object.keys(covariates);
|
|
93
|
+
const result = {
|
|
94
|
+
rows, type: [], diffUn: [], diffAdj: [], vRatioUn: [], vRatioAdj: [],
|
|
95
|
+
observations: {
|
|
96
|
+
rows: ["All (ESS)", "All (Unweighted)", "Matched (ESS)", "Matched (Unweighted)", "Unmatched", ...(withDiscarded ? ["Discarded"] : [])],
|
|
97
|
+
control: [], treated: [],
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
for (const name of rows) {
|
|
101
|
+
const v = covariates[name];
|
|
102
|
+
if (v.length !== n)
|
|
103
|
+
throw new RangeError(`covariate '${name}' must have the length of 'tr'`);
|
|
104
|
+
if (v.some((x) => !Number.isFinite(x)))
|
|
105
|
+
throw new RangeError(`covariate '${name}' has missing or infinite values`);
|
|
106
|
+
const isBinary = new Set(v).size <= 2 && v.every((x) => x === 0 || x === 1);
|
|
107
|
+
// a continuous covariate rescaled exactly: its standardised differences and variance ratios do not change
|
|
108
|
+
const vs = isBinary ? v : rescaled(v).values;
|
|
109
|
+
const [m1, var1] = moments(vs, null, g, true);
|
|
110
|
+
const [m0, var0] = moments(vs, null, g, false);
|
|
111
|
+
const spread = isBinary ? [m1 * (1 - m1), m0 * (1 - m0)] : [var1, var0];
|
|
112
|
+
const s = estimand === "ATT" ? Math.sqrt(spread[0]) : estimand === "ATC" ? Math.sqrt(spread[1])
|
|
113
|
+
: Math.sqrt((spread[0] + spread[1]) / 2);
|
|
114
|
+
const scale = isBinary && binary === "raw" ? 1 : s;
|
|
115
|
+
result.type.push(isBinary ? "Binary" : "Contin.");
|
|
116
|
+
// a difference of 0 is 0 (cobalt's, also for a constant covariate whose SD is 0)
|
|
117
|
+
result.diffUn.push(m1 === m0 ? 0 : (m1 - m0) / scale);
|
|
118
|
+
// a zero control variance gives NA in cobalt (not Inf)
|
|
119
|
+
result.vRatioUn.push(isBinary || var0 === 0 ? NaN : var1 / var0);
|
|
120
|
+
if (weights === undefined) {
|
|
121
|
+
result.diffAdj.push(NaN);
|
|
122
|
+
result.vRatioAdj.push(NaN);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const [a1, av1] = moments(vs, weights, g, true);
|
|
126
|
+
const [a0, av0] = moments(vs, weights, g, false);
|
|
127
|
+
result.diffAdj.push(a1 === a0 ? 0 : (a1 - a0) / scale);
|
|
128
|
+
result.vRatioAdj.push(isBinary || av0 === 0 ? NaN : av1 / av0);
|
|
129
|
+
}
|
|
130
|
+
for (const group of [false, true]) {
|
|
131
|
+
let count = 0, sw = 0, sw2 = 0, positive = 0, gone = 0;
|
|
132
|
+
for (let i = 0; i < n; i++) {
|
|
133
|
+
if (g[i] !== group)
|
|
134
|
+
continue;
|
|
135
|
+
count++;
|
|
136
|
+
if (discarded.has(i + 1))
|
|
137
|
+
gone++;
|
|
138
|
+
if (weights === undefined)
|
|
139
|
+
continue;
|
|
140
|
+
const wi = weights[i];
|
|
141
|
+
sw += wi;
|
|
142
|
+
sw2 += wi * wi;
|
|
143
|
+
if (wi > 0)
|
|
144
|
+
positive++;
|
|
145
|
+
}
|
|
146
|
+
const matched = weights === undefined ? [NaN, NaN, NaN] : [sw * sw / sw2, positive, count - positive - gone];
|
|
147
|
+
if (withDiscarded)
|
|
148
|
+
matched.push(gone);
|
|
149
|
+
(group ? result.observations.treated : result.observations.control).push(count, count, ...matched);
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Standardised mean difference of one variable between two groups. Equivalent to `tableone::ExtractSmd()` in R. The
|
|
155
|
+
* call followed is `ExtractSmd(CreateTableOne(vars, strata, data, factorVars))` with two groups. Missing values (`NaN`,
|
|
156
|
+
* `null`) are left out.
|
|
157
|
+
*
|
|
158
|
+
* Numeric: `|mean1 − mean0| / sqrt((s1² + s0²) / 2)` with the groups' SDs (divisor `n − 1`). Categorical
|
|
159
|
+
* (`factor: true`): Yang and Dalton's `sqrt(d' S⁻¹ d)`, `d` the differences of the proportions of the levels after the
|
|
160
|
+
* first, `S` the mean of the two groups' multinomial covariance matrices `p_k (δ_kl − p_l)`; with two levels
|
|
161
|
+
* `|p1 − p0| / sqrt((p1(1 − p1) + p0(1 − p0)) / 2)`. 0 when both the difference and the spread are 0. When `S` is
|
|
162
|
+
* singular (a level in one group only) the generalised inverse is used, as tableone; when `S` is 0 (one level in each
|
|
163
|
+
* group) the result is NaN, as tableone.
|
|
164
|
+
* @category Causal inference
|
|
165
|
+
* @example
|
|
166
|
+
* ```ts
|
|
167
|
+
* tableOneSmd([1, 2, 3, 2, 5, 4], [0, 0, 0, 1, 1, 1]); // 1.2909944487358056
|
|
168
|
+
* tableOneSmd(["a", "b", "a", "b", "b", "b"], [0, 0, 0, 1, 1, 1], { factor: true }); // 2
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
export function tableOneSmd(x, group, options = {}) {
|
|
172
|
+
checkOptions(options, TABLE_ONE_SMD_KEYS, "tableOneSmd"); // generated: option-keys.mjs
|
|
173
|
+
const { factor = false } = options;
|
|
174
|
+
if (x.length !== group.length)
|
|
175
|
+
throw new RangeError("'x' and 'group' must have the same length");
|
|
176
|
+
const glev = [...new Set(group)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
177
|
+
if (glev.length !== 2)
|
|
178
|
+
throw new RangeError("'group' must have exactly two levels");
|
|
179
|
+
const keep = (v) => v !== null && !(typeof v === "number" && Number.isNaN(v));
|
|
180
|
+
const parts = glev.map((lv) => x.filter((v, i) => group[i] === lv && keep(v)));
|
|
181
|
+
if (!factor) {
|
|
182
|
+
if (parts.flat().some((e) => typeof e !== "number"))
|
|
183
|
+
throw new TypeError("'x' must be numeric unless factor: true");
|
|
184
|
+
// rescaled exactly as one column (the SMD does not change)
|
|
185
|
+
const all = rescaled(parts.flat()).values;
|
|
186
|
+
const split = [all.slice(0, parts[0].length), all.slice(parts[0].length)];
|
|
187
|
+
const stats = split.map((v) => {
|
|
188
|
+
const mean = v.reduce((s, e) => s + e, 0) / v.length;
|
|
189
|
+
return [mean, v.reduce((s, e) => s + (e - mean) * (e - mean), 0) / (v.length - 1)];
|
|
190
|
+
});
|
|
191
|
+
const diff = stats[1][0] - stats[0][0];
|
|
192
|
+
const sd = Math.sqrt((stats[0][1] + stats[1][1]) / 2);
|
|
193
|
+
return diff === 0 ? 0 : Math.abs(diff) / sd;
|
|
194
|
+
}
|
|
195
|
+
const levels = [...new Set(parts.flat())].sort((a, b) => (typeof a === "number" && typeof b === "number" ? a - b
|
|
196
|
+
: String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0));
|
|
197
|
+
const props = parts.map((p) => levels.slice(1).map((lv) => p.filter((e) => e === lv).length / p.length));
|
|
198
|
+
const d = props[1].map((q, k) => q - props[0][k]);
|
|
199
|
+
if (d.every((e) => e === 0))
|
|
200
|
+
return 0;
|
|
201
|
+
const K = d.length;
|
|
202
|
+
const S = Array.from({ length: K }, (_, k) => Array.from({ length: K }, (_, l) => {
|
|
203
|
+
const c = (p) => (k === l ? p[k] * (1 - p[k]) : -p[k] * p[l]);
|
|
204
|
+
return (c(props[0]) + c(props[1])) / 2;
|
|
205
|
+
}));
|
|
206
|
+
// S is singular when a level is in one group only: tableone's value is then that of the generalised inverse
|
|
207
|
+
// (MASS::ginv's; experiments/psm112-edge.json factorAbsent), and NaN when S is 0 (each group has one level)
|
|
208
|
+
if (S.every((row) => row.every((v) => v === 0)))
|
|
209
|
+
return NaN;
|
|
210
|
+
const Si = ginv(S);
|
|
211
|
+
let q = 0;
|
|
212
|
+
for (let k = 0; k < K; k++)
|
|
213
|
+
for (let l = 0; l < K; l++)
|
|
214
|
+
q += d[k] * Si[k][l] * d[l];
|
|
215
|
+
return Math.sqrt(q);
|
|
216
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** The population the matching estimates for: the treated (ATT), everyone (ATE) or the controls (ATC).
|
|
2
|
+
* @category Causal inference
|
|
3
|
+
*/
|
|
4
|
+
export type MatchEstimand = "ATT" | "ATE" | "ATC";
|
|
5
|
+
/** Options of {@link match}. Equivalent to the arguments of the Matching package's `Match()` with `ties = FALSE` and
|
|
6
|
+
* `replace = FALSE`.
|
|
7
|
+
* @category Causal inference
|
|
8
|
+
*/
|
|
9
|
+
export interface MatchOptions {
|
|
10
|
+
/** The estimand (default `"ATT"`): the treated units are matched (ATT), the controls (ATC), or both (ATE). */
|
|
11
|
+
estimand?: MatchEstimand;
|
|
12
|
+
/** The number of matches for each matched unit (default 1), a positive integer. */
|
|
13
|
+
M?: number;
|
|
14
|
+
/**
|
|
15
|
+
* The caliper in standard deviations of `x` (the SD with divisor n over all units, as R's `ecaliper`): a match
|
|
16
|
+
* farther than `caliper * sd` is not made, and a unit with fewer than `M` controls within it is dropped.
|
|
17
|
+
*/
|
|
18
|
+
caliper?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Result of {@link match}. The fields are those of R's `Match` object, with 1-based row numbers.
|
|
21
|
+
* @category Causal inference
|
|
22
|
+
*/
|
|
23
|
+
export interface MatchResult {
|
|
24
|
+
/** Rows (1-based) of the treated unit of each pair. */
|
|
25
|
+
indexTreated: number[];
|
|
26
|
+
/** Rows (1-based) of the control unit of each pair. */
|
|
27
|
+
indexControl: number[];
|
|
28
|
+
/** Weight of each pair: `1 / M`. */
|
|
29
|
+
weights: number[];
|
|
30
|
+
/**
|
|
31
|
+
* Rows (1-based) of the dropped units that appear in no pair (R's `index.dropped`), only when a caliper is given;
|
|
32
|
+
* `null` otherwise or when none. Under ATE a dropped unit can still be another unit's match and is then not listed.
|
|
33
|
+
* Without a caliper R lists none even when units are dropped (`ndrops` counts them).
|
|
34
|
+
*/
|
|
35
|
+
indexDropped: number[] | null;
|
|
36
|
+
/** The caliper as given (in standard deviations), `null` without one. */
|
|
37
|
+
caliper: number | null;
|
|
38
|
+
/** The caliper on the scale of `x` (R's `ecaliper`), `null` without one. */
|
|
39
|
+
ecaliper: number | null;
|
|
40
|
+
/** Number of units (R's `nobs`). */
|
|
41
|
+
nobs: number;
|
|
42
|
+
/** Number of matched units (R's `wnobs`: units that found their matches). */
|
|
43
|
+
wnobs: number;
|
|
44
|
+
/** Number of matched-for units left without matches, for either reason (R's `ndrops`). */
|
|
45
|
+
ndrops: number;
|
|
46
|
+
/** The estimand. */
|
|
47
|
+
estimand: MatchEstimand;
|
|
48
|
+
/** The number of matches per matched unit. */
|
|
49
|
+
M: number;
|
|
50
|
+
/**
|
|
51
|
+
* Size of each candidate set from which matches were drawn at random (more candidates than needed at equal
|
|
52
|
+
* distance), in the order of the draws. Empty when there were no ties; the pairs are then R's. With sets of 2 only
|
|
53
|
+
* the pairs and the random numbers used are also R's; larger sets are broken by rStats.js's own rule (see
|
|
54
|
+
* {@link match}).
|
|
55
|
+
*/
|
|
56
|
+
tieSizes: number[];
|
|
57
|
+
/** Warnings (R's, e.g. when no unit could be matched). */
|
|
58
|
+
warnings: string[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Nearest-neighbour matching on a scalar score, without replacement and with random tie-breaking. Equivalent to
|
|
62
|
+
* `Matching::Match()` in R. The call followed is
|
|
63
|
+
* `Match(Tr = tr, X = x, estimand, M, caliper, ties = FALSE, replace = FALSE)`, used with the linear predictor
|
|
64
|
+
* `logit(PS)` of a propensity score model.
|
|
65
|
+
*
|
|
66
|
+
* The matched units (the treated for ATT, the controls for ATC, all for ATE) are processed in data order. Each takes
|
|
67
|
+
* its matches from the units of the other group not yet used: every available unit within the M-th smallest distance
|
|
68
|
+
* is a candidate (within the caliper when one is given), and when there are more candidates than M, M of them are
|
|
69
|
+
* drawn at random. A unit with fewer than M available candidates is dropped. Pairs are listed in the order of the
|
|
70
|
+
* matched units, the controls of one treated unit (ATT) in row order.
|
|
71
|
+
*
|
|
72
|
+
* Random draws use rStats.js's generator (`setSeed`): one uniform `u` for each pick, and the candidate at 0-based
|
|
73
|
+
* index `floor(k (1 - u))` among the `k` remaining (in row order) is taken. Without ties no random number is used and
|
|
74
|
+
* the pairs are R's; with sets of two candidates the rule is R's (the second when `u < 0.5`). Known differences from
|
|
75
|
+
* R: larger tie sets are broken differently (R's rule is not documented), and distances count as tied only when
|
|
76
|
+
* exactly equal (R also treats distances within `distance.tolerance = 1e-5` as ties). `M` below 1 is an error (R
|
|
77
|
+
* warns and uses 1).
|
|
78
|
+
* @category Causal inference
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* const m = match([1, 0, 1, 0, 0], [0.2, 0.1, 1.5, 1.4, 3]);
|
|
82
|
+
* m.indexTreated; // [1, 3]
|
|
83
|
+
* m.indexControl; // [2, 4]
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export declare function match(tr: readonly (number | boolean)[], x: readonly number[], options?: MatchOptions): MatchResult;
|