@numero-uno-jpn/rstats 1.18.0 → 1.19.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 +14 -0
- package/README.ja.md +5 -5
- package/README.md +5 -5
- package/dist/causal.js +2 -2
- package/dist/chunks/{chunk-LY5XGFPU.js → chunk-2S45NNTL.js} +2 -2
- package/dist/chunks/{chunk-HRRCC2BD.js → chunk-4JFGT4PN.js} +2 -2
- package/dist/chunks/{chunk-ICDW3I2F.js → chunk-4JRJU5F5.js} +2 -2
- package/dist/chunks/{chunk-GIK34P23.js → chunk-5NW4WT4F.js} +2 -2
- package/dist/chunks/{chunk-W5M3R4NH.js → chunk-6ZGEYAFC.js} +2 -2
- package/dist/chunks/{chunk-RXYZQ3UX.js → chunk-7D7FBLWD.js} +2 -2
- package/dist/chunks/{chunk-IKMW63BE.js → chunk-ANFN3X2M.js} +2 -2
- package/dist/chunks/{chunk-N7BUE54L.js → chunk-AS2XTRHH.js} +2 -2
- package/dist/chunks/{chunk-53WQDB3C.js → chunk-BJ5WAL2C.js} +2 -2
- package/dist/chunks/{chunk-HMLYEFQN.js → chunk-CEOSH3H2.js} +2 -2
- package/dist/chunks/{chunk-FLFNMSHI.js → chunk-CMNKXRZF.js} +2 -2
- package/dist/chunks/{chunk-GEHMND3C.js → chunk-CNJLPH6W.js} +2 -2
- package/dist/chunks/{chunk-VATAUY7N.js → chunk-DXSVV47D.js} +2 -2
- package/dist/chunks/{chunk-JF4PXFJE.js → chunk-FAKOND5W.js} +2 -2
- package/dist/chunks/{chunk-H6Z7JVSD.js → chunk-FCGTZ6BD.js} +2 -2
- package/dist/chunks/{chunk-IOJVFYHW.js → chunk-FELX2TZZ.js} +2 -2
- package/dist/chunks/{chunk-NOTJ45G3.js → chunk-G4B2SQR6.js} +2 -2
- package/dist/chunks/{chunk-IW4S634O.js → chunk-HPIZAWMT.js} +2 -2
- package/dist/chunks/{chunk-HGAEVPVS.js → chunk-I5XUWUEV.js} +2 -2
- package/dist/chunks/{chunk-3JFRDXN7.js → chunk-ILQ4VWSD.js} +2 -2
- package/dist/chunks/{chunk-6I23C2YJ.js → chunk-JLFRYDYO.js} +2 -2
- package/dist/chunks/{chunk-MVPHISOV.js → chunk-JXKHFSGK.js} +1 -1
- package/dist/chunks/{chunk-HG4LJBNV.js → chunk-LBU73UMS.js} +2 -2
- package/dist/chunks/{chunk-QUD3374N.js → chunk-LSZTDKIB.js} +2 -2
- package/dist/chunks/{chunk-LCIX76FR.js → chunk-LWFKGF43.js} +2 -2
- package/dist/chunks/{chunk-MKZH65DK.js → chunk-M5J3DHXB.js} +2 -2
- package/dist/chunks/{chunk-WYVUCQO3.js → chunk-MOYWWJP4.js} +1 -1
- package/dist/chunks/{chunk-KJMLQHCY.js → chunk-MPBFXHXT.js} +1 -1
- package/dist/chunks/{chunk-IBHMM2SL.js → chunk-NWNJEAKI.js} +2 -2
- package/dist/chunks/{chunk-EC77KAAM.js → chunk-OTETSONJ.js} +2 -2
- package/dist/chunks/{chunk-SCFFHEDZ.js → chunk-QH4GK3JN.js} +2 -2
- package/dist/chunks/{chunk-JPWYGTUN.js → chunk-QVE7V5UG.js} +2 -2
- package/dist/chunks/{chunk-V6FMGGUV.js → chunk-RMGEIU4Z.js} +2 -2
- package/dist/chunks/{chunk-Z33Q545U.js → chunk-SAFH76DR.js} +2 -2
- package/dist/chunks/{chunk-5CTWYFMB.js → chunk-SJJJ7Y4X.js} +2 -2
- package/dist/chunks/{chunk-NDZVVNBB.js → chunk-TVU4N6BA.js} +2 -2
- package/dist/chunks/{chunk-CTZUYKVL.js → chunk-U6RXYALO.js} +2 -2
- package/dist/chunks/{chunk-MXZ64QME.js → chunk-VNLSP22M.js} +2 -2
- package/dist/chunks/{chunk-XUMVTGMM.js → chunk-W4EITKLJ.js} +2 -2
- package/dist/chunks/{chunk-XQCHC3SH.js → chunk-WWRKCRTZ.js} +1 -1
- package/dist/chunks/{chunk-2JB7F646.js → chunk-XHHDBEHB.js} +2 -2
- package/dist/chunks/{chunk-YXMHWS5R.js → chunk-XJMBX6A2.js} +2 -2
- package/dist/chunks/{chunk-KVJBCT3D.js → chunk-YZ6SBFFG.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions/normal.d.ts +4 -0
- package/dist/distributions/normal.js +4 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +1 -0
- package/dist/entries/tests.js +1 -0
- package/dist/htest/timeROC.d.ts +564 -0
- package/dist/htest/timeROC.js +1106 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- 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 +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,20 @@ 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.19.0 - 2026-11-26
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Time-dependent ROC** in `/tests` (after the timeROC and survivalROC packages, values only, no plots): `timeROC`
|
|
15
|
+
(cumulative/dynamic AUC, TP and FP at several times; inverse probability of censoring weights from the Kaplan-Meier
|
|
16
|
+
of the censoring, a Cox model or Aalen's additive model with other markers; competing risks with definitions (i) and
|
|
17
|
+
(ii); the iid representation and standard errors), `timeROCConfint` (pointwise intervals and the simultaneous band by
|
|
18
|
+
the multiplier bootstrap), `timeROCCompare` (two markers on the same subjects, with p-values adjusted for the several
|
|
19
|
+
times), `seSpPPVNPV` (time-dependent sensitivity, specificity and predictive values of a cutpoint, with standard
|
|
20
|
+
errors), `timeROCAucCurve` (the values of `plotAUCcurve`), `timeROCAucDiff` (the difference of two AUCs with its
|
|
21
|
+
interval; not in R) and `survivalROC` (Heagerty, Lumley and Pepe's Kaplan-Meier estimator; the nearest-neighbour
|
|
22
|
+
estimator is not offered).
|
|
23
|
+
|
|
10
24
|
## 1.18.0 - 2026-11-26
|
|
11
25
|
|
|
12
26
|
### 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.19.0。** R の stats パッケージの数値計算の中心
|
|
20
20
|
(分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
|
|
21
21
|
[ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
|
|
22
22
|
|
|
@@ -235,7 +235,7 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
|
|
|
235
235
|
| 分割表と比率 | `binomCI`、`binomDiffCI`、`binomRatioCI` (DescTools の `BinomCI`、`BinomDiffCI`、`BinomRatioCI`)、`oddsRatio` (epitools と epiR のスコア区間)、`fisherTest(x, { midp: true })` (exact2x2)、`boschlooTest` (Exact)、`gTest`、`stuartMaxwellTest`、`goodmanKruskalGamma` (DescTools)、`lblTest` (coin)、`chisqTest(x, { nMinus1: true })` (Campbell の N − 1 検定) と Freeman-Tukey 残差、`tost` (equivalence)、`binomDiffEquivalenceTest` (2 つの比率のスコア法の TOST) |
|
|
236
236
|
| 多重比較 | `dscfAllPairsTest` (Steel-Dwass)、`kwAllPairsDunnTest`、`kwManyOneDunnTest`、`manyOneUTest` (Steel の多対一の順位検定)、`dunnettTest`、`gamesHowellTest`、`tukeyTest` (PMCMRplus)、`dunnTest` (dunn.test)、`glhtDunnett` (multcomp) |
|
|
237
237
|
| 生存時間解析 | `survdiff` (log-rank と G-rho 族)、`survfit` (Kaplan-Meier と Nelson-Aalen・Fleming-Harrington の累積ハザード、重み (逆確率重みも)、ロバスト標準誤差、信頼区間、中央値、制限平均、計数過程データ)、`rmst2` (非調整・共変量調整の制限平均生存時間と制限平均損失時間)、`coxph` (Cox 回帰。Efron と Breslow のタイ、ケース重み、層、Wald・尤度比・スコア検定、計数過程データ、ロバスト分散と `cluster`)、`survfitCoxph` (Cox の当てはめの共変量の値ごとの調整生存曲線: `survfit(coxph, newdata)`)、`clogit` (マッチした組の条件付きロジスティック回帰: 正確な尤度と近似の尤度)、`coxZph` (比例ハザード性の検定)、`cuminc`・`timepoints` (累積発生率と Gray の検定)、`crr`・`predictCrr` (Fine-Gray 回帰と予測)、`survreg`・`survregPredict`・`survregResiduals` (パラメトリックな加速故障時間回帰) |
|
|
238
|
-
| 診断の精度と測定法の比較 | `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
|
+
| 診断の精度と測定法の比較 | `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 回帰)。時間依存 ROC: `timeROC` (timeROC: 累積/動的の AUC、打ち切りの重みは Kaplan-Meier・Cox・Aalen、競合リスク、iid 表現による標準誤差)、`timeROCConfint`、`timeROCCompare`、`timeROCAucCurve`、`timeROCAucDiff`、`seSpPPVNPV`、`survivalROC` (survivalROC の Kaplan-Meier 推定量) |
|
|
239
239
|
| 一致度と信頼性 | `kappa2`、`kappamFleiss`、`icc` (irr)、`ICC` (psych: Shrout と Fleiss の 6 つの形式)、`cronbachAlpha`、`partialR` (psych)、`polychor`、`polyserial` (polycor)、`pbvnorm`、`factanal`、`omega` (McDonald の ω。psych) |
|
|
240
240
|
| データの扱い | `completeCases` (`complete.cases`)、`naOmit` (`na.omit`)、`subset`、`merge`、データフレームの `rbind`・`cbind`、`tapply`、`split`、`aggregate`、`pivotLonger` と `pivotWider` (tidyr)、`fromRows` と `toRows` (行のオブジェクトの配列とデータフレームの相互の変換)。検定の formula 版 (`tTest("y ~ g", data)`、`kruskalTest`、`friedmanTest("y ~ w \| b", data)`、`corTest("~ x + y", data)` など) |
|
|
241
241
|
| 線形代数 | `matMul` (`%*%`), `add`, `subtract`, `multiply`, `divide`, `outer`, `t`, `diag`, `cbind`, `rbind`, `matrix`, `kronecker`, `seq`, `crossprod`, `tcrossprod`, `norm`, `backsolve`, `forwardsolve`, `chol`, `chol2inv`, `qr` と `qrQ`, `qrR`, `qrX`, `qrCoef`, `qrQy`, `qrQty`, `qrResid`, `qrFitted`, `qrSolve` (`qr.Q` …), `solve`, `det`, `determinant`, `rcond`, `kappa`, `svd`, `eigen`, `lu`, `prcomp`, `ginv` (MASS)、`schur`、`expm` |
|
|
@@ -302,7 +302,7 @@ double-double 演算で計算しているためです。詳しくは [docs/ja/ac
|
|
|
302
302
|
| `lmer` (`/mixed` から) / `lmerSummary`・`lmerContest`・`lmerAnova` も | 19.4 / 70.0 KB |
|
|
303
303
|
| `glmer` (`/mixed` から) / `glmerSummary`・`glmerAnova`・`glmerPredict` も | 47.2 / 66.1 KB |
|
|
304
304
|
| `polr` / `rlm` / `nls` (`/regression` から) | 25.0 / 14.6 / 8.0 KB |
|
|
305
|
-
| すべて (`/mixed` と `/regression` を除く) |
|
|
305
|
+
| すべて (`/mixed` と `/regression` を除く) | 348.2 KB |
|
|
306
306
|
|
|
307
307
|
(`npm run size` で測れます。)
|
|
308
308
|
|
|
@@ -312,12 +312,12 @@ double-double 演算で計算しているためです。詳しくは [docs/ja/ac
|
|
|
312
312
|
`/regression` の `polr`・`rlm`・`nls` とその関数は、この方法でしか import できません。メインの入口には含めていません)。
|
|
313
313
|
|
|
314
314
|
バンドラを使わない場合は、1 ファイルにまとめたビルド `dist/rstats.js` (`/mixed` と `/regression` 以外のすべての関数を含む
|
|
315
|
-
minify 済みの ES モジュール、gzip で
|
|
315
|
+
minify 済みの ES モジュール、gzip で 348 KB) を jsDelivr から読み込めます。jsDelivr は、npm のリリースを
|
|
316
316
|
そのまま配信します。
|
|
317
317
|
|
|
318
318
|
```html
|
|
319
319
|
<script type="module">
|
|
320
|
-
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.19.0/dist/rstats.js";
|
|
321
321
|
console.log(pnorm(1.96)); // ≈ 0.9750021049
|
|
322
322
|
</script>
|
|
323
323
|
```
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ R-compatible statistical functions for JavaScript and the browser, written in Ty
|
|
|
14
14
|
- **Runs anywhere.** ESM only, no dependencies, no Node-specific APIs, tree-shakable
|
|
15
15
|
(`pnorm` alone is 1.6 KB gzipped).
|
|
16
16
|
|
|
17
|
-
Status: **1.
|
|
17
|
+
Status: **1.19.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
|
|
|
@@ -233,7 +233,7 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
|
|
|
233
233
|
| Contingency tables and proportions | `binomCI`, `binomDiffCI`, `binomRatioCI` (DescTools' `BinomCI`, `BinomDiffCI`, `BinomRatioCI`), `oddsRatio` (epitools, and epiR's score interval), `fisherTest(x, { midp: true })` (exact2x2), `boschlooTest` (Exact), `gTest`, `stuartMaxwellTest`, `goodmanKruskalGamma` (DescTools), `lblTest` (coin), `chisqTest(x, { nMinus1: true })` (Campbell's 'N − 1' test) and Freeman-Tukey residuals, `tost` (equivalence), `binomDiffEquivalenceTest` (score TOST of two proportions) |
|
|
234
234
|
| Multiple comparisons | `dscfAllPairsTest` (Steel-Dwass), `kwAllPairsDunnTest`, `kwManyOneDunnTest`, `manyOneUTest` (Steel's many-one rank test), `dunnettTest`, `gamesHowellTest`, `tukeyTest` (PMCMRplus), `dunnTest` (dunn.test), `glhtDunnett` (multcomp) |
|
|
235
235
|
| Survival analysis | `survdiff` (log-rank and the G-rho family), `survfit` (Kaplan-Meier and Nelson-Aalen/Fleming-Harrington cumulative hazards, weights (also inverse probability weights), robust standard errors, confidence intervals, medians, restricted means and counting-process data), `rmst2` (unadjusted and covariate-adjusted restricted mean survival time and time lost), `coxph` (Cox regression: Efron and Breslow ties, case weights, strata, Wald, likelihood-ratio and score tests, counting-process data, robust variance and `cluster`), `survfitCoxph` (adjusted survival curves of a Cox fit for covariate profiles: `survfit(coxph, newdata)`), `clogit` (conditional logistic regression for matched sets: exact and approximate likelihoods), `coxZph` (proportional-hazards tests), `cuminc` and `timepoints` (cumulative incidence and Gray's tests), `crr` and `predictCrr` (Fine-Gray regression and predictions), `survreg`, `survregPredict` and `survregResiduals` (parametric accelerated-failure-time regression) |
|
|
236
|
-
| 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
|
+
| 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); time-dependent ROC: `timeROC` (timeROC: cumulative/dynamic AUC with Kaplan-Meier, Cox or Aalen censoring weights, competing risks, iid standard errors), `timeROCConfint`, `timeROCCompare`, `timeROCAucCurve`, `timeROCAucDiff`, `seSpPPVNPV`, `survivalROC` (survivalROC's Kaplan-Meier estimator) |
|
|
237
237
|
| Agreement and reliability | `kappa2`, `kappamFleiss`, `icc` (irr), `ICC` (psych: the six forms of Shrout and Fleiss), `cronbachAlpha`, `partialR` (psych), `polychor`, `polyserial` (polycor), `pbvnorm`, `factanal`, `omega` (McDonald's ω, psych) |
|
|
238
238
|
| Data handling | `completeCases` (`complete.cases`), `naOmit` (`na.omit`), `subset`, `merge`, `rbind` and `cbind` of data frames, `tapply`, `split`, `aggregate`, `pivotLonger` and `pivotWider` (tidyr), `fromRows` and `toRows` (a data frame from an array of row objects and back); formula forms of the tests (`tTest("y ~ g", data)`, `kruskalTest`, `friedmanTest("y ~ w \| b", data)`, `corTest("~ x + y", data)`, ...) |
|
|
239
239
|
| Linear algebra | `matMul` (`%*%`), `add`, `subtract`, `multiply`, `divide`, `outer`, `t`, `diag`, `cbind`, `rbind`, `matrix`, `kronecker`, `seq`, `crossprod`, `tcrossprod`, `norm`, `backsolve`, `forwardsolve`, `chol`, `chol2inv`, `qr` with `qrQ`, `qrR`, `qrX`, `qrCoef`, `qrQy`, `qrQty`, `qrResid`, `qrFitted`, `qrSolve` (`qr.Q` …), `solve`, `det`, `determinant`, `rcond`, `kappa`, `svd`, `eigen`, `lu`, `prcomp`, `ginv` (MASS), `schur`, `expm` |
|
|
@@ -301,7 +301,7 @@ removed. Approximate sizes after minification and gzip:
|
|
|
301
301
|
| `lmer` (from `/mixed`) / with `lmerSummary`, `lmerContest`, `lmerAnova` | 19.4 / 70.0 KB |
|
|
302
302
|
| `glmer` (from `/mixed`) / with `glmerSummary`, `glmerAnova`, `glmerPredict` | 47.2 / 66.1 KB |
|
|
303
303
|
| `polr` / `rlm` / `nls` (from `/regression`) | 25.0 / 14.6 / 8.0 KB |
|
|
304
|
-
| everything (except `/mixed` and `/regression`) |
|
|
304
|
+
| everything (except `/mixed` and `/regression`) | 348.2 KB |
|
|
305
305
|
|
|
306
306
|
(`npm run size` measures these.)
|
|
307
307
|
|
|
@@ -312,11 +312,11 @@ Each area is also a subpath export, for importing one area without the rest:
|
|
|
312
312
|
areas are only available this way, not from the main entry point.
|
|
313
313
|
|
|
314
314
|
Without a bundler, load the single-file build `dist/rstats.js` (one minified ES module with every
|
|
315
|
-
function except those of `/mixed` and `/regression`,
|
|
315
|
+
function except those of `/mixed` and `/regression`, 348 KB gzipped) from jsDelivr, which serves each npm release:
|
|
316
316
|
|
|
317
317
|
```html
|
|
318
318
|
<script type="module">
|
|
319
|
-
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.19.0/dist/rstats.js";
|
|
320
320
|
console.log(pnorm(1.96)); // ≈ 0.9750021049
|
|
321
321
|
</script>
|
|
322
322
|
```
|
package/dist/causal.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 1.
|
|
2
|
-
import{a as Fe,b as Ne}from"./chunks/chunk-3JFRDXN7.js";import{p as Pe,x as ne,y as re}from"./chunks/chunk-HMLYEFQN.js";import{a as Ie}from"./chunks/chunk-EC77KAAM.js";import{a as ae}from"./chunks/chunk-VATAUY7N.js";import{h as ke}from"./chunks/chunk-QUD3374N.js";import{a as ge}from"./chunks/chunk-KVJBCT3D.js";import{b as Xe}from"./chunks/chunk-XUMVTGMM.js";import{f as Ue,h as ve,j as Be}from"./chunks/chunk-IOJVFYHW.js";import"./chunks/chunk-Z33Q545U.js";import"./chunks/chunk-WYVUCQO3.js";import"./chunks/chunk-CTZUYKVL.js";import"./chunks/chunk-NOTJ45G3.js";import{a as Ge}from"./chunks/chunk-RXYZQ3UX.js";import{d as te}from"./chunks/chunk-H6Z7JVSD.js";import"./chunks/chunk-JPWYGTUN.js";import"./chunks/chunk-IBHMM2SL.js";import{a as Ke}from"./chunks/chunk-GIK34P23.js";import{C as ue,w as He,x as Ce}from"./chunks/chunk-IW4S634O.js";import"./chunks/chunk-LY5XGFPU.js";import"./chunks/chunk-IKMW63BE.js";import{a as Re}from"./chunks/chunk-MXZ64QME.js";import{e as De,f as Ve,g as ze,m as We,n as we,o as be}from"./chunks/chunk-N7BUE54L.js";import"./chunks/chunk-XQCHC3SH.js";import"./chunks/chunk-KJMLQHCY.js";import"./chunks/chunk-YXMHWS5R.js";import"./chunks/chunk-53WQDB3C.js";import{r as qe,s as Z,t as fe}from"./chunks/chunk-GEHMND3C.js";import{h as ee,k as B,l as Te}from"./chunks/chunk-HG4LJBNV.js";import{l as K}from"./chunks/chunk-MVPHISOV.js";function Ye(e){let s=0;for(let n of e)Math.abs(n)>s&&(s=Math.abs(n));return s>0&&Number.isFinite(s)?Math.floor(Math.log2(s)):0}function ie(e){let s=Ye(e),n=e.map(o=>ee(o,-s)),t=n[0]??0,r=n.map(o=>o-t),m=Ye(r);return{values:r.map(o=>ee(o,-m)),unitExp:s+m}}var Et=["estimand","M","caliper"];function Mt(e,s,n={}){K(n,Et,"match");let{estimand:t="ATT",M:r=1,caliper:m}=n,o=e.length;if(s.length!==o)throw new RangeError("length(Tr) != nrow(X)");if(t!=="ATT"&&t!=="ATE"&&t!=="ATC")throw new RangeError(`invalid 'estimand': ${String(t)}`);if(!Number.isInteger(r)||r<1)throw new RangeError("'M' must be a positive integer");if(m!==void 0&&!(m>0&&Number.isFinite(m)))throw new RangeError("'caliper' must be a positive number");let l=[];for(let g=0;g<o;g++){let A=e[g];if(A===!0||A===1)l.push(!0);else if(A===!1||A===0)l.push(!1);else throw typeof A=="number"&&Number.isNaN(A)?new RangeError("Match(): input includes NAs"):new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");if(!Number.isFinite(s[g]))throw new RangeError("Match(): input includes NAs")}if(!l.includes(!0)||!l.includes(!1))throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");let i=0;for(let g of s)i=Math.max(i,Math.abs(g));let c=i>0?Math.floor(Math.log2(i)):0,a=s.map(g=>ee(g,-c)),u=null,E=1/0;if(m!==void 0){let{values:g,unitExp:A}=ie(a),S=0;for(let O of g)S+=O;S/=o;let C=0;for(let O of g)C+=(O-S)*(O-S);let $=ee(Math.sqrt(C/o),A);E=m*$,u=ee(E,c)}let b=[new Array(o).fill(!1),new Array(o).fill(!1)],f=[],d=[],y=[],M=[],v=0,p=0;for(let g=0;g<o;g++){let A=l[g];if(A?t==="ATC":t==="ATT")continue;let S=b[A?0:1],C=[];for(let x=0;x<o;x++){if(l[x]===A)continue;let F=Math.abs(a[g]-a[x]);F>E||S[x]||C.push({j:x,d:F})}if(C.length<r){p++,y.push(g+1);continue}let O=C.map(x=>x.d).sort((x,F)=>x-F)[r-1],j=C.filter(x=>x.d<=O).map(x=>x.j),V;if(j.length===r)V=j;else{M.push(j.length),V=[],j=j.slice();for(let x=0;x<r;x++){let F=j.length,D=Math.min(F-1,Math.floor(F*(1-ze())));V.push(j[D]),j.splice(D,1)}V.sort((x,F)=>x-F)}for(let x of V)S[x]=!0,f.push((A?g:x)+1),d.push((A?x:g)+1);v++}let h=new Set([...f,...d]),T=u===null?[]:y.filter(g=>!h.has(g)),w=[];return f.length===0&&w.push("'Match' object contains no valid matches (probably because of the caliper or the exact option)."),{indexTreated:f,indexControl:d,weights:f.map(()=>1/r),indexDropped:T.length>0?T:null,caliper:m??null,ecaliper:u,nobs:o,wnobs:v,ndrops:p,estimand:t,M:r,tieSizes:M,warnings:w}}var At=["match","weightit","weights","estimand","levels","binary"],Tt=["factor"];function Je(e){let s=new Array(e.nobs).fill(0);return e.indexTreated.forEach((n,t)=>{s[n-1]+=e.weights[t],s[e.indexControl[t]-1]+=e.weights[t]}),s}function Nt(e,s){if(e===!0||e===1)return!0;if(e===!1||e===0)return!1;throw new RangeError(`'tr' must be 0 or 1 (element ${s+1})`)}function he(e,s,n,t){let r=0,m=0,o=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];r+=a,m+=a*a,o+=a*e[c]}let l=o/r,i=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];i+=a*(e[c]-l)*(e[c]-l)}return[l,i/(r-m/r)]}function Rt(e,s,n={}){K(n,At,"balTab");let{match:t,weightit:r,binary:m="raw",levels:o={}}=n;if(t!==void 0&&r!==void 0)throw new RangeError("give 'match' or 'weightit', not both");let l=t!==void 0?Je(t):r!==void 0?r.weights:n.weights,i=t?.estimand??r?.estimand??n.estimand??"ATT",c=new Set(t?.indexDropped??[]),a=t!==void 0&&t.caliper!==null,u=e.length,E=e.map(Nt);if(!E.includes(!0)||!E.includes(!1))throw new RangeError("'tr' must contain both groups");if(l!==void 0&&l.length!==u)throw new RangeError("'weights' must have the length of 'tr'");if(i==="ATO"&&l===void 0)throw new RangeError("estimand 'ATO' needs the weights");let b=[];r?.ps&&b.push(["prop.score",r.ps,"Distance"]);for(let[M,v]of Object.entries(s)){if(v.length!==u)throw new RangeError(`covariate '${M}' must have the length of 'tr'`);if(v.every(h=>typeof h=="number")){b.push([M,v,null]);continue}if(!v.every(h=>typeof h=="string"))throw new TypeError(`covariate '${M}' must be all numbers or all strings`);let p=o[M]??[...new Set(v)].sort(Re);if(v.some(h=>!p.includes(h)))throw new RangeError(`covariate '${M}' has values not among its levels`);for(let h of p.length===2?p.slice(1):p)b.push([`${M}_${h}`,v.map(T=>T===h?1:0),null])}let f=E.map(()=>!0),d=r!==void 0,y={rows:b.map(([M])=>M),type:[],diffUn:[],diffAdj:[],vRatioUn:[],vRatioAdj:[],observations:{rows:d?["Unadjusted","Adjusted"]:["All (ESS)","All (Unweighted)","Matched (ESS)","Matched (Unweighted)","Unmatched",...a?["Discarded"]:[]],control:[],treated:[]}};for(let[M,v,p]of b){if(v.some(D=>!Number.isFinite(D)))throw new RangeError(`covariate '${M}' has missing or infinite values`);let h=p===null&&new Set(v).size<=2&&v.every(D=>D===0||D===1),T=h?null:ie(v),w=T===null?v:T.values,[g,A]=he(w,null,E,!0),[S,C]=he(w,null,E,!1),$;if(i==="ATO"){let[D,Q]=he(w,l,f,!0);$=Math.sqrt(h?D*(1-D):Q)}else{let D=h?[g*(1-g),S*(1-S)]:[A,C];if($=Math.sqrt(i==="ATT"?D[0]:i==="ATC"?D[1]:(D[0]+D[1])/2),ee($,T?.unitExp??0)<Math.sqrt(Number.EPSILON)){let[Q,z]=he(w,null,f,!0);$=Math.sqrt(h?Q*(1-Q):z)}}let O=h&&m==="raw"?1:$;if(y.type.push(p??(h?"Binary":"Contin.")),y.diffUn.push(g===S?0:(g-S)/O),y.vRatioUn.push(h||C===0?NaN:A/C),l===void 0){y.diffAdj.push(NaN),y.vRatioAdj.push(NaN);continue}let[j,V]=he(w,l,E,!0),[x,F]=he(w,l,E,!1);y.diffAdj.push(j===x?0:(j-x)/O),y.vRatioAdj.push(h||F===0?NaN:V/F)}for(let M of[!1,!0]){let v=0,p=0,h=0,T=0,w=0;for(let S=0;S<u;S++){if(E[S]!==M||(v++,c.has(S+1)&&w++,l===void 0))continue;let C=l[S];p+=C,h+=C*C,C>0&&T++}let g=M?y.observations.treated:y.observations.control;if(d){g.push(v,p*p/h);continue}let A=l===void 0?[NaN,NaN,NaN]:[p*p/h,T,v-T-w];a&&A.push(w),g.push(v,v,...A)}return y}function St(e,s,n={}){K(n,Tt,"tableOneSmd");let{factor:t=!1}=n;if(e.length!==s.length)throw new RangeError("'x' and 'group' must have the same length");let r=[...new Set(s)].sort((f,d)=>f<d?-1:f>d?1:0);if(r.length!==2)throw new RangeError("'group' must have exactly two levels");let m=f=>f!==null&&!(typeof f=="number"&&Number.isNaN(f)),o=r.map(f=>e.filter((d,y)=>s[y]===f&&m(d)));if(!t){if(o.flat().some(p=>typeof p!="number"))throw new TypeError("'x' must be numeric unless factor: true");let f=ie(o.flat()).values,y=[f.slice(0,o[0].length),f.slice(o[0].length)].map(p=>{let h=p.reduce((T,w)=>T+w,0)/p.length;return[h,p.reduce((T,w)=>T+(w-h)*(w-h),0)/(p.length-1)]}),M=y[1][0]-y[0][0],v=Math.sqrt((y[0][1]+y[1][1])/2);return M===0?0:Math.abs(M)/v}let l=[...new Set(o.flat())].sort((f,d)=>typeof f=="number"&&typeof d=="number"?f-d:String(f)<String(d)?-1:String(f)>String(d)?1:0),i=o.map(f=>l.slice(1).map(d=>f.filter(y=>y===d).length/f.length)),c=i[1].map((f,d)=>f-i[0][d]);if(c.every(f=>f===0))return 0;let a=c.length,u=Array.from({length:a},(f,d)=>Array.from({length:a},(y,M)=>{let v=p=>d===M?p[d]*(1-p[d]):-p[d]*p[M];return(v(i[0])+v(i[1]))/2}));if(u.every(f=>f.every(d=>d===0)))return NaN;let E=Xe(u),b=0;for(let f=0;f<a;f++)for(let d=0;d<a;d++)b+=c[f]*E[f][d]*c[d];return Math.sqrt(b)}var Ot=["method","link","estimand","stabilize"],xt=["at","lower","treat"],oe=Number.EPSILON;function Ct(e){return e.map((s,n)=>{if(s===!0||s===1)return 1;if(s===!1||s===0)return 0;throw new RangeError(`'tr' must be 0 or 1 (element ${n+1})`)})}function kt(e,s){let n=[],t=[],r={};for(let[m,o]of Object.entries(e)){if(o.length!==s)throw new RangeError(`covariate '${m}' must have the length of 'tr'`);if(o.every(c=>typeof c=="number")){let c=o;if(c.some(a=>!Number.isFinite(a)))throw new RangeError(`covariate '${m}' has missing or infinite values`);n.push(m),t.push(c.slice());continue}if(!o.every(c=>typeof c=="string"))throw new TypeError(`covariate '${m}' must be all numbers or all strings`);let l=o,i=[...new Set(l)].sort(Re);r[m]=i;for(let c of i.slice(1))n.push(m+c),t.push(l.map(a=>a===c?1:0))}return{names:n,columns:t,factors:r}}function Qe(e){return e.map(s=>{let n=s.reduce((r,m)=>r+m,0)/s.length,t=s.reduce((r,m)=>Math.max(r,Math.abs(m-n)),0);return s.map(r=>t>0?(r-n)/t:0)})}function $t(e){let s=e[0]?.length??0,n=[new Array(s).fill(1/Math.sqrt(s))],t=[];for(let r of e){let m=Math.sqrt(r.reduce((i,c)=>i+c*c,0)),o=r.slice();for(let i=0;i<2;i++)for(let c of n){let a=o.reduce((u,E,b)=>u+E*c[b],0);for(let u=0;u<s;u++)o[u]-=a*c[u]}let l=Math.sqrt(o.reduce((i,c)=>i+c*c,0));l>1e-7*m&&(n.push(o.map(i=>i/l)),t.push(r))}return t}function st(e,s){let n=s.length,t=e.map((o,l)=>[...o,s[l]]),r=0;for(let o of e)for(let l of o)r=Math.max(r,Math.abs(l));for(let o=0;o<n;o++){let l=o;for(let i=o+1;i<n;i++)Math.abs(t[i][o])>Math.abs(t[l][o])&&(l=i);if(!(Math.abs(t[l][o])>1e-13*r))return null;[t[o],t[l]]=[t[l],t[o]];for(let i=o+1;i<n;i++){let c=t[i][o]/t[o][o];if(c!==0)for(let a=o;a<=n;a++)t[i][a]-=c*t[o][a]}}let m=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let l=t[o][n];for(let i=o+1;i<n;i++)l-=t[o][i]*m[i];m[o]=l/t[o][o]}return m}function $e(e,s){return Array.from({length:s},(n,t)=>[1,...e.map(r=>r[t])])}function Ze(e,s,n){let t=n.length,r=new Array(t).fill(0);r[0]=Math.log(n[0]/s.length);let m=c=>{let a=0;for(let u of s)a+=Math.exp(e[u].reduce((E,b,f)=>E+b*c[f],0));return a-n.reduce((u,E,b)=>u+E*c[b],0)},o=m(r),l=!1,i=1e-13*Math.max(1,Math.abs(n[0]));for(let c=0;c<200;c++){let a=n.map(p=>-p),u=Array.from({length:t},()=>new Array(t).fill(0));for(let p of s){let h=e[p],T=Math.exp(h.reduce((w,g,A)=>w+g*r[A],0));for(let w=0;w<t;w++){a[w]+=T*h[w];for(let g=0;g<=w;g++)u[w][g]+=T*h[w]*h[g]}}for(let p=0;p<t;p++)for(let h=p+1;h<t;h++)u[p][h]=u[h][p];let E=Math.max(...a.map(Math.abs));if(E<=i){l=!0;break}let b=st(u,a.map(p=>-p));if(b===null||b.some(p=>!Number.isFinite(p)))break;let f=1e-12*(Math.abs(o)+1),d=1,y=r.map((p,h)=>p+b[h]),M=m(y);for(;!(M<=o+f)&&d>1e-10;)d/=2,y=r.map((p,h)=>p+d*b[h]),M=m(y);if(!(M<=o+f))break;let v=b.some((p,h)=>Math.abs(d*p)>1e-15*Math.max(1,Math.abs(r[h])));if(r.splice(0,t,...y),o=M,!v){l=E<=1e-9*Math.max(1,Math.abs(n[0]));break}}return{eta:e.map(c=>c.reduce((a,u,E)=>a+u*r[E],0)),converged:l}}var Lt={logit:{p:e=>te(e),q:e=>te(-e),d:e=>te(e)*te(-e)},probit:{p:e=>Z(e),q:e=>Z(-e),d:e=>qe(e)}};function _t(e,s,n,t,r){let m=s.length,o=r.length,l=r.slice(),i=d=>{let y=new Array(o).fill(0),M=Array.from({length:o},()=>new Array(o).fill(0));for(let v=0;v<m;v++){let p=e[v],h=p.reduce(($,O,j)=>$+O*d[j],0),T=t.p(h),w=t.q(h),g=t.d(h),A=s[v],S,C;n==="ATE"?(S=A?1/T:-1/w,C=A?-g/(T*T):-g/(w*w)):n==="ATT"?(S=A?1:-T/w,C=A?0:-g/(w*w)):n==="ATC"?(S=A?w/T:-1,C=A?-g/(T*T):0):(S=A?w:-T,C=-g);for(let $=0;$<o;$++){y[$]+=S*p[$];for(let O=0;O<o;O++)M[$][O]+=C*p[$]*p[O]}}return{g:y,J:M}},c=d=>d.reduce((y,M)=>y+M*M,0),{g:a,J:u}=i(l),E=c(a),b=!1,f=1e-12*m;for(let d=0;d<200;d++){if(Math.max(...a.map(Math.abs))<=f){b=!0;break}let y=st(u,a.map(T=>-T));if(y===null||y.some(T=>!Number.isFinite(T)))break;let M=1,v=l.map((T,w)=>T+y[w]),p=i(v),h=c(p.g);for(;!(h<E)&&M>1e-10;)M/=2,v=l.map((T,w)=>T+M*y[w]),p=i(v),h=c(p.g);if(!(h<E)){b=Math.max(...a.map(Math.abs))<=1e-8*m;break}l=v,a=p.g,u=p.J,E=h}return{eta:e.map(d=>d.reduce((y,M,v)=>y+M*l[v],0)),converged:b}}function et(e,s,n,t){switch(e){case"ATE":return s?1/n:1/t;case"ATT":return s?1:n/t;case"ATC":return s?t/n:1;default:return s?t:n}}var jt={glm:"glm.fit: algorithm did not converge",cbps:"The covariate balancing conditions could not be solved, so the covariates will not be exactly balanced.",ipt:"The optimization failed to converge; consider using fewer covariates or a different link function.",ebal:"The estimated weights do not balance the covariates, indicating the optimization arrived at a degenerate solution. Try decreasing the number of variables supplied to the optimization."},tt={cbps:"covariate balancing propensity score weighting",ipt:"inverse probability tilting",ebal:"entropy balancing"};function qt(e,s,n={}){K(n,Ot,"weightit");let{method:t="glm",estimand:r="ATE",stabilize:m=!1}=n,o=t==="ps"?"glm":t;if(!["glm","cbps","ipt","ebal"].includes(o))throw new RangeError(`unknown method '${String(t)}'`);if(!["ATE","ATT","ATC","ATO"].includes(r))throw new RangeError(`unknown estimand '${String(r)}'`);let l=o==="ebal"?null:n.link??"logit";if(l!==null&&!{glm:["logit","probit","cauchit","cloglog"],cbps:["logit","probit"],ipt:["logit"]}[o].includes(l))throw new RangeError(`link '${l}' is not available for method '${o}'`);if((o==="ipt"||o==="ebal")&&r==="ATO")throw new RangeError(`"ATO" is not an allowable estimand for ${tt[o]} with a binary treatment. Only "ATE", "ATT", and "ATC" are allowed.`);let c=[];if(m&&o==="glm"&&r!=="ATE")throw new RangeError('`stabilize` can only be supplied when `estimand = "ATE"`.');m&&o!=="glm"&&c.push(`\`stabilize\` cannot be used with ${tt[o]} and will be ignored.`);let a=Ct(e),u=a.length;if(!a.includes(0)||!a.includes(1))throw new RangeError("The treatment must have at least two unique values.");let{names:E,columns:b}=kt(s,u);if(b.length===0)throw new RangeError("'covariates' must have at least one column");let f=$t(b.map(w=>ie(w).values)),d=a.flatMap((w,g)=>w?[g]:[]),y=a.flatMap((w,g)=>w?[]:[g]),M=a.map((w,g)=>g),v=r==="ATT"?1:r==="ATC"?0:null,p=null,h,T=!0;if(o==="glm"){let w=be(()=>ve($e(f,u).map(g=>g.slice(1)),a,{family:"binomial",link:l}));T=w.converged,p=w.fittedValues.map((g,A)=>l==="logit"&&Math.abs(w.linearPredictors[A])>30?w.linearPredictors[A]>0?1-oe:oe:Math.min(Math.max(g,oe),1-oe)),h=a.map((g,A)=>et(r,g,p[A],1-p[A])),p.some(g=>g<=10*oe||g>=1-10*oe)&&c.push("Propensity scores numerically equal to 0 or 1 were estimated, indicating perfect separation. These may yield problems with inference. See `?method_glm` (`?WeightIt::method_glm()`) for details.")}else if(o==="cbps"){let w=Qe(f),g=$e(w,u),A=be(()=>ve(g.map(O=>O.slice(1)),a,{family:"binomial",link:l})).coefficients.map(O=>Number.isFinite(O)?O:0),S=Lt[l],C=_t(g,a,r,S,A);T=C.converged;let $=O=>Math.min(Math.max(O,oe),1-oe);p=C.eta.map(O=>$(S.p(O))),h=a.map((O,j)=>et(r,O,p[j],$(S.q(C.eta[j]))))}else{let w=Qe(f),g=$e(w,u),A=j=>g[0].map((V,x)=>j.reduce((F,D)=>F+g[D][x],0)),S={C:r!=="ATC",T:r!=="ATT"},C=o==="ebal"&&r==="ATE"?{C:A(M),T:A(M)}:{C:A(d),T:A(y)},$=S.C?Ze(g,y,C.C):null,O=S.T?Ze(g,d,C.T):null;if(T=($?.converged??!0)&&(O?.converged??!0),o==="ebal")h=a.map((j,V)=>j?O?Math.exp(O.eta[V]):1:$?Math.exp($.eta[V]):1);else{let j=r==="ATE"?1:0;h=a.map((V,x)=>V?O?j+Math.exp(O.eta[x]):1:$?j+Math.exp($.eta[x]):1),p=a.map((V,x)=>r==="ATT"?te($.eta[x]):r==="ATC"?te(-O.eta[x]):V?te(-O.eta[x]):te($.eta[x]))}}if(T||c.push(jt[o]),m&&o==="glm"){let w=[y.length/u,d.length/u];h=h.map((g,A)=>g*w[a[A]])}return h.every(w=>Math.abs(w-1)<Math.sqrt(oe))&&c.push("All weights are 1, possibly indicating an estimation failure."),we("weightit",{weights:h,ps:p,treat:a,estimand:r,method:o,link:l,stabilized:m&&o==="glm",focal:v,columnNames:E,converged:T,warnings:c})}function nt(e,s,n,t){let r=e.slice();if(s.length===0)return r;let m=s.map(i=>e[i]),o,l;if(n<1){let i=n<.5?1-n:n;o=ae(m,i,{type:3}),l=ae(m,1-i,{type:3})}else{if(!Number.isInteger(n))throw new RangeError("'at' must be below 1 or a whole number");if(n>=m.length)return null;let i=n>m.length/2?m.length-n:n,c=m.slice().sort((a,u)=>a-u);o=c[c.length-1-i],l=c[i]}for(let i of s)e[i]>o&&(r[i]=o),t&&e[i]<l&&(r[i]=l);return r}var ot=e=>`\`at\` must be less than ${e}, the number of units. Weights will not be trimmed.`;function Ht(e,s){K(s,xt,"trimWeights");let{at:n,lower:t=!1}=s;if(!(n>0)||!Number.isFinite(n))throw new RangeError("'at' must be a positive number");if(Array.isArray(e)||ArrayBuffer.isView(e)){let l=Array.from(e);if(s.treat!==void 0&&s.treat.length!==l.length)throw new RangeError("'treat' must have the length of 'w'");let i=nt(l,l.map((c,a)=>a),n,t);return i===null?(We("trimWeights",[ot(l.length)]),l):i}let r=e,m=r.treat.flatMap((l,i)=>r.focal===null||l!==r.focal?[i]:[]),o=nt(r.weights,m,n,t);return o===null?we("trimWeights",{...r,weights:r.weights.slice(),warnings:[ot(m.length)]}):{...r,weights:o,warnings:r.warnings.slice()}}function rt(e,s){let n=s.map(a=>e[a]),t=n.length,r=0,m=0;for(let a of n)r+=a,m+=a*a;let o=r/t,l=n.reduce((a,u)=>a+(u-o)*(u-o),0),i=n.map(a=>o>0?a/o:NaN),c=n.map((a,u)=>u).sort((a,u)=>n[u]-n[a]||a-u).slice(0,5).reverse();return{range:[Math.min(...n),Math.max(...n)],top:{index:c.map(a=>s[a]+1),weights:c.map(a=>n[a])},mean:o,coefOfVar:Math.sqrt(l/(t-1))/o,scaledMad:i.reduce((a,u)=>a+Math.abs(u-1),0)/t,negativeEntropy:i.reduce((a,u)=>a+(Number.isNaN(u)?NaN:u>0?u*Math.log(u):0),0)/t,numZeros:n.filter(a=>Math.abs(a)<1e-10).length,n:t,ess:r*r/m}}function Dt(e){let s=e.treat.flatMap((t,r)=>t?[r]:[]),n=e.treat.flatMap((t,r)=>t?[]:[r]);return{treated:rt(e.weights,s),control:rt(e.weights,n),stabilized:e.stabilized}}var Vt=new Set(["treat","mediator","treatValue","controlValue","covariates","sims","boot","bootCiType","confLevel","robustSE"]);function at(e,s,n){let t=Ue(e);if(t===void 0||typeof e.formula!="string")throw new TypeError(`the ${n} model must be a formula fit of lm or glm`);if(t.weights!==void 0||t.offset!==void 0)throw new RangeError(`weights and offsets are not supported (the ${n} model)`);let r="family"in e,m=a=>a;if(r){let a=e;if(a.family==="binomial"&&(a.link==="logit"||a.link==="probit"))m=Be(a).linkinv;else if(!(a.family==="gaussian"&&a.link==="identity"))throw new RangeError(`the ${n} model's family is not supported (binomial with logit or probit, or gaussian)`)}if(e.coefficients.some(a=>Number.isNaN(a)))throw new RangeError(`the ${n} model has aliased coefficients`);let o=e.formula,l=Ge(Ke(o,!1,!1,!0),s,{...t.contrasts===void 0?{}:{contrasts:t.contrasts},...t.levels===void 0?{}:{levels:t.levels},dropUnusedLevels:!0,anyResponse:!0}),i=r?e.model.rows:e.rows,c=r?e.model.columnNames:e.coefNames;if(l.frame.rows.length!==i.length||l.frame.rows.some((a,u)=>a!==i[u])||l.colNames.join("\0")!==c.join("\0"))throw new RangeError(`the data do not give the ${n} model's rows and columns (pass the data it was fitted on)`);return{fit:e,isGlm:r,formula:o,options:t,coef:e.coefficients.slice(),names:c,linkinv:m,d:l,rows:i}}function ye(e,s,n,t){let r=e.d.terms.variables.indexOf(s);if(r<0){if(t)throw new RangeError(`'${s}' is not a variable of the ${n} model`);return-1}if(e.d.frame.variables[r].kind!=="numeric")throw new RangeError(`'${s}' must be numeric in the ${n} model`);return r}function ut(e,s,n){let t=e.d.frame.variables.map((r,m)=>{let o=s.get(m);return o===void 0?r:{kind:"numeric",values:typeof o=="number"?new Array(n).fill(o):o.slice()}});return e.d.rowsOf(t,n)}var ce=(e,s)=>{let n=0;for(let t=0;t<e.length;t++)n+=e[t]*s[t];return n};function it(e,s,n,t){let r=e.length,m=2**-1022,o=Number.MAX_VALUE;if(s.some((a,u)=>a.some(E=>!Number.isFinite(E))||!(a[u]>=m&&a[u]<=o)))throw new RangeError(`the ${t} model's coefficient covariance is out of the double range (rescale the variables, or use boot: true)`);let l=Fe(s),i=ue(n*r),c=[];for(let a=0;a<n;a++){let u=[];for(let E=0;E<r;E++){let b=0;for(let f=0;f<r;f++)b+=i[a*r+f]*l[f][E];u.push(e[E]+b)}c.push(u)}return c}function Oe(e,s){let n=new Map(e.mCov);return n.set(e.mTreat,s),ut(e.m,n,e.n)}function Me(e,s,n){let t=new Map(e.yCov);return t.set(e.yTreat,s),t.set(e.yMed,n),ut(e.y,t,e.n)}function Se(e,s,n,t){return Me(e,s,n).map(r=>e.y.linkinv(ce(r,t)))}var Ee=(e,s)=>B(e.map((n,t)=>n-s[t]));function ht(e,s,n,t){if(xe(e.y)){let i=Me(e,e.t0,s),c=Me(e,e.t0,n),a=Me(e,e.t1,s),u=Me(e,e.t1,n),E=(b,f)=>B(b.map((d,y)=>{let M=0;for(let v=0;v<d.length;v++)M+=(d[v]-f[y][v])*t[v];return M}));return[E(i,c),E(a,u),E(u,c),E(a,i),E(a,c)]}let r=Se(e,e.t0,s,t),m=Se(e,e.t0,n,t),o=Se(e,e.t1,s,t),l=Se(e,e.t1,n,t);return[Ee(r,m),Ee(o,l),Ee(l,m),Ee(o,r),Ee(o,m)]}function Le(e,s,n,t){let r=e.n,m=Oe(e,e.t1).map(c=>ce(c,s)),o=Oe(e,e.t0).map(c=>ce(c,s)),l,i;if(xe(e.m)){let c=ue(r,{sd:n});l=m.map((a,u)=>a+c[u]),i=o.map((a,u)=>a+c[u])}else l=m.map(c=>ge(1,e.m.linkinv(c))),i=o.map(c=>ge(1,e.m.linkinv(c)));return ht(e,l,i,t)}var xe=e=>!e.isGlm||e.fit.family==="gaussian",_e=e=>e.isGlm?Math.sqrt(zt(e.fit)):e.fit.sigma;function zt(e){let s=0;for(let n=0;n<e.residuals.length;n++)s+=e.weights[n]*e.residuals[n]**2;return s/e.dfResidual}var ct=(e,s,n)=>{let t=ae(e,[s,n],{type:7});return[t[0],t[1]]};function je(e,s,n,t){K(t,Vt,"mediate");let{treat:r,mediator:m}=t;if(typeof r!="string"||typeof m!="string")throw new TypeError("'treat' and 'mediator' are required");let o=t.treatValue??1,l=t.controlValue??0;if(!Number.isFinite(o)||!Number.isFinite(l))throw new RangeError("treatValue and controlValue must be finite");let i=Math.trunc(t.sims??1e3),c=t.boot??!1,a=t.bootCiType??"perc";if(a!=="perc"&&a!=="bca")throw new RangeError('bootCiType must be "perc" or "bca"');let u=t.confLevel??.95;if(!(u>0&&u<1))throw new RangeError("confLevel must be in (0, 1)");let E=t.robustSE??!1;if(!(i>=2))throw new RangeError("sims must be at least 2");let b=[];c&&E&&b.push("'robustSE' is ignored for nonparametric bootstrap");let f=at(e,n,"mediator"),d=at(s,n,"outcome");if(!xe(f)&&e.family!=="binomial")throw new RangeError("unsupported mediator model");if(f.d.terms.variables[0]!==m)throw new RangeError(`the mediator model's response must be '${m}'`);if(f.rows.length!==d.rows.length||f.rows.some((N,k)=>N!==d.rows[k]))throw new RangeError("number of observations do not match between mediator and outcome models");let y=f.rows.length,M=Object.entries(t.covariates??{});for(let[,N]of M)if(!Number.isFinite(N))throw new RangeError("covariate values must be finite");let v={m:f,y:d,treat:r,mediator:m,t1:o,t0:l,n:y,mTreat:ye(f,r,"mediator",!0),yTreat:ye(d,r,"outcome",!0),yMed:ye(d,m,"outcome",!0),mCov:M.map(([N,k])=>[ye(f,N,"mediator",!1),k]).filter(([N])=>N>=0),yCov:M.map(([N,k])=>[ye(d,N,"outcome",!1),k]).filter(([N])=>N>=0)};if(M.some(([N])=>!f.d.terms.variables.includes(N)&&!d.d.terms.variables.includes(N)))throw new RangeError("covariates must be variables of the models");let p=xe(f),h,T;if(c){let N=Ie(y,{size:y*i,replace:!0}),k=[...new Set([...f.d.terms.variables,...d.d.terms.variables])],I=p?_e(f):NaN;Le(v,f.coef,I,d.coef),h=[];for(let P=0;P<i;P++){let G=Array.from({length:y},(H,L)=>f.rows[N[P+L*i]]),X=Object.fromEntries(k.map(H=>{let L=n[H];return[H,G.map(R=>L[R])]})),Y=lt(f,X),J=lt(d,X);h.push(Le(v,ft(Y,f,b),p?_e({...f,fit:Y,isGlm:"family"in Y}):NaN,ft(J,d,b)))}T=Le(v,f.coef,I,d.coef)}else{let N=E?re(e,{type:"HC3"}).vcov:ne(e).vcov,k=E?re(s,{type:"HC3"}).vcov:ne(s).vcov,I=it(f.coef,N,i,"mediator"),P=it(d.coef,k,i,"outcome"),G=Oe(v,o),X=Oe(v,l),Y=Array.from({length:i},()=>new Array(y)),J=Array.from({length:i},()=>new Array(y));if(p){let H=ue(i*y,{sd:_e(f)});for(let L=0;L<y;L++)for(let R=0;R<i;R++)Y[R][L]=ce(G[L],I[R])+H[L*i+R],J[R][L]=ce(X[L],I[R])+H[L*i+R]}else{for(let H=0;H<y;H++)for(let L=0;L<i;L++)Y[L][H]=ge(1,f.linkinv(ce(G[H],I[L])));for(let H=0;H<y;H++)for(let L=0;L<i;L++)J[L][H]=ge(1,f.linkinv(ce(X[H],I[L])))}h=I.map((H,L)=>ht(v,Y[L],J[L],P[L]))}let w=N=>h.map(k=>k[N]),g=w(0),A=w(1),S=w(2),C=w(3),$=w(4),O=g.map((N,k)=>N/$[k]),j=A.map((N,k)=>N/$[k]),V=g.map((N,k)=>(N+A[k])/2),x=S.map((N,k)=>(N+C[k])/2),F=O.map((N,k)=>(N+j[k])/2),D=(1-u)/2,Q=(1+u)/2,z=(N,k)=>{let I;if(c&&a==="bca"){let X=B(N),Y=0,J=0,H=0;for(let q of N){let W=X-q;Y+=W*W,J+=W*W*W,q<X&&H++}let L=J/(6*Y**1.5),R=fe(H/N.length),_=q=>Z(R+(R+q)/(1-L*(R+q)));I=ct(N,_(fe(D)),_(fe(Q)))}else I=ct(N,D,Q);let P=0,G=0;for(let X of N)X>0?P++:X<0&&G++;return{estimate:k,ci:I,p:2*Math.min(P/N.length,G/N.length),sims:N}},U;if(T===void 0){let N=ke(O),k=ke(j);U=[B(g),B(A),B(S),B(C),B($),N,k,B(V),B(x),(N+k)/2]}else{let[N,k,I,P,G]=T;U=[N,k,I,P,G,N/G,k/G,(N+k)/2,(I+P)/2,(N/G+k/G)/2]}let le=d.d.terms.termLabels.some(N=>{let k=N.split(":");return k.length>1&&k.includes(r)&&k.includes(m)});return we("mediate",{d0:z(g,U[0]),d1:z(A,U[1]),z0:z(S,U[2]),z1:z(C,U[3]),tau:z($,U[4]),n0:z(O,U[5]),n1:z(j,U[6]),dAvg:z(V,U[7]),zAvg:z(x,U[8]),nAvg:z(F,U[9]),treatValue:o,controlValue:l,nobs:y,sims:i,boot:c,bootCiType:a,confLevel:u,robustSE:E&&!c,INT:le,warnings:b})}function lt(e,s){let n={...e.options};return be(()=>e.isGlm?ve(e.formula,s,n):Pe(e.formula,s,n))}var mt='prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';function ft(e,s,n){let t="family"in e?e.model.columnNames:e.coefNames;return s.names.map(r=>{let m=t.indexOf(r);return m<0||Number.isNaN(e.coefficients[m])?(n.includes(mt)||n.push(mt),0):e.coefficients[m]})}var It=["pred","modx","modxValues","johnsonNeyman","jnAlpha","ciWidth","robust"],Ft=["pred","modx","alpha","robust"];function dt(e,s,n,t,r){if(typeof n!="string"||typeof t!="string")throw new TypeError("'pred' and 'modx' are required");if(r!==!1&&r!=="HC3")throw new RangeError('robust must be false or "HC3"');let m="family"in e,o=m?e.model.columnNames:e.coefNames;if(o===void 0)throw new TypeError("the model must be a formula fit of lm or glm");if(m&&e.family!=="binomial"&&e.family!=="gaussian")throw new RangeError("the model's family is not supported (binomial or gaussian)");let l=[`${n}:${t}`,`${t}:${n}`].find(d=>o.includes(d));if(!o.includes(n)||l===void 0)throw new RangeError(`the model has no coefficients '${n}' and '${n}:${t}'`);let i=r==="HC3"?re(e,{type:"HC3"}):ne(e),c=i.names.indexOf(n),a=i.names.indexOf(l);if(c<0||a<0)throw new RangeError("the predictor's or the interaction's coefficient is aliased");let u=e.coefficients,E=m?e.model.rows:e.rows,b=s[t];if(b===void 0)throw new RangeError(`object '${t}' not found`);let f=E.map(d=>Number(b[d]));if(f.some(d=>!Number.isFinite(d)))throw new RangeError(`'${t}' must be numeric`);return{b1:u[o.indexOf(n)],b3:u[o.indexOf(l)],v11:i.vcov[c][c],v13:i.vcov[c][a],v33:i.vcov[a][a],df:e.dfResidual,isGlm:m&&e.family==="binomial",w:f}}function pt(e,s){if(!(s>0&&s<1))throw new RangeError("alpha must be in (0, 1)");let n=Ce(1-s/2,e.df),t=n*n,r=2**-1022,m=Number.MAX_VALUE;if(![e.v11,e.v33].every(A=>A>=r&&A<=m)||!Number.isFinite(e.v13))throw new RangeError("the model's coefficient covariance is out of the double range (rescale the variables)");let o=2**Math.round(Math.log2(e.v11)/2),l=2**Math.round((Math.log2(e.v11)-Math.log2(e.v33))/2),i=e.b1/o,c=e.b3/o*l,a=e.v11/o/o,u=e.v13/o/o*l,E=e.v33/o/o*l*l,b=c*c-t*E,f=2*(i*c-t*u),d=i*i-t*a,y=f*f-4*b*d,M=Math.min(...e.w),v=Math.max(...e.w),p=[M,v],h,T=!1;if(!(y>=0))h=[-1/0,1/0],T=!0;else{let A=Math.sqrt(y),S=(-f-Math.sign(f||1)*A)/(2*b),C=S===0?(-f+Math.sign(f||1)*A)/(2*b):d/(b*S);h=S<=C?[S*l,C*l]:[C*l,S*l]}let w=!T&&b<0,g=!(h[0]>M&&h[0]<v)&&!(h[1]>M&&h[1]<v);return{bounds:h,inside:w,failed:T,allSig:g,modrange:p,alpha:s}}function Wt(e,s,n){return K(n,Ft,"johnsonNeyman"),pt(dt(e,s,n.pred,n.modx,n.robust??!1),n.alpha??.05)}function Kt(e,s,n){K(n,It,"simSlopes");let t=dt(e,s,n.pred,n.modx,n.robust??!1),r=n.ciWidth??.95;if(!(r>0&&r<1))throw new RangeError("ciWidth must be in (0, 1)");let m=n.modxValues??"mean-plus-minus",o;if(m==="mean-plus-minus"){let b=B(t.w),f=Math.sqrt(Te(t.w));o=[b-f,b,b+f]}else if(Array.isArray(m)&&m.every(b=>Number.isFinite(b)))o=[...m];else throw new RangeError('modxValues must be "mean-plus-minus" or finite numbers');let l=t.isGlm?fe((1+r)/2):Ce((1+r)/2,t.df),i=o.map(b=>t.b1+t.b3*b),c=o.map(b=>Math.sqrt(t.v11+2*b*t.v13+b*b*t.v33)),a=i.map((b,f)=>b/c[f]),u=a.map(b=>2*(t.isGlm?Z(-Math.abs(b)):He(-Math.abs(b),t.df))),E={values:o,estimate:i,se:c,lower:i.map((b,f)=>b-l*c[f]),upper:i.map((b,f)=>b+l*c[f]),statistic:a,statisticName:t.isGlm?"z":"t",p:u};return(n.johnsonNeyman??!0)&&(E.jn=pt(t,n.jnAlpha??.05)),E}var Gt=["treat","mediator"],Ut=["nmc","confLevel","treat","mediator"],Pt=new Set(["moderator","treatValue","controlValue","wLow","wHigh","method","nmc","sims","confLevel","robustSE","treat","mediator"]);function de(e,s){let n=22250738585072014e-324,t=Number.MAX_VALUE;if(e.some((r,m)=>r.some(o=>!Number.isFinite(o))||!(r[m]>=n&&r[m]<=t)))throw new RangeError(`the ${s} model's coefficient covariance is out of the double range (rescale the variables)`)}function Ae(e,s,n){let t=ne(e),r=t.names.indexOf(s);if(r<0)throw new RangeError(`the ${n} model has no coefficient '${s}'`);let m="family"in e?e.model.columnNames:e.coefNames;return{value:e.coefficients[m.indexOf(s)],v:t.vcov[r][r],names:t.names,vcov:t.vcov}}function Bt(e,s,n){K(n,Gt,"sobelTest");let t=Ae(e,n.treat,"mediator"),r=Ae(s,n.mediator,"outcome");de([[t.v]],"mediator"),de([[r.v]],"outcome");let m=t.value,o=r.value,l=Math.sqrt(t.v),i=Math.sqrt(r.v),c=m*o,a=Math.hypot(o*l,m*i),u=c/a;return{a:m,sa:l,b:o,sb:i,ab:c,se:a,z:u,p:2*Z(Math.abs(u),{lowerTail:!1})}}var bt=(e,s)=>{let n=1-s,t=ae(e,[n/2,1-n/2],{type:7});return[t[0],t[1]]};function vt(e){if(!(e>0&&e<1))throw new RangeError("confLevel must be in (0, 1)")}function Xt(e,s,n){K(n,Ut,"mediationMonteCarlo");let t=Math.trunc(n.nmc??2e4),r=n.confLevel??.95;if(vt(r),!(t>=2))throw new RangeError("nmc must be at least 2");let m=Ae(e,n.treat,"mediator"),o=Ae(s,n.mediator,"outcome"),l=Ae(s,n.treat,"outcome"),i=o.names.indexOf(n.mediator),c=o.names.indexOf(n.treat);de([[m.v]],"mediator"),de([[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]],"outcome");let a=ue(t,{mean:m.value,sd:Math.sqrt(m.v)}),u=Ne(t,[o.value,l.value],[[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]]),E=a.map((p,h)=>p*u[h][0]),b=u.map(p=>p[1]),f=E.map((p,h)=>p+b[h]),d=E.map((p,h)=>p/f[h]),y=m.value*o.value,M=l.value,v=(p,h)=>({estimate:p,ci:bt(h,r),sims:h});return{indirect:v(y,E),direct:v(M,b),total:v(y+M,f),proportion:v(y/(y+M),d)}}function gt(e,s,n){let t=e[n];if(t===void 0)throw new RangeError(`object '${n}' not found`);let r=s.map(i=>Number(t[i]));if(r.some(i=>!Number.isFinite(i)))throw new RangeError(`'${n}' must be numeric`);let m=[...new Set(r)].sort((i,c)=>i-c);if(m.length===2)return[m[0],m[1]];let o=B(r),l=Math.sqrt(Te(r));return[o-l,o+l]}var wt=e=>!("family"in e)||e.family==="gaussian",Yt=e=>"family"in e?e.model.rows:e.rows;function Jt(e,s,n,t){K(t,Pt,"moderatedMediation");let{treat:r,mediator:m,moderator:o}=t;if(typeof r!="string"||typeof m!="string"||typeof o!="string")throw new TypeError("'treat', 'mediator' and 'moderator' are required");let l=t.confLevel??.95;vt(l);let i=Yt(e),[c,a]=gt(n,i,r),[u,E]=gt(n,i,o),b=t.treatValue??a,f=t.controlValue??c,d=t.wLow??u,y=t.wHigh??E,M=t.method??(wt(e)&&wt(s)?"monteCarlo":"mediate"),v=(R,_)=>({estimate:R,ci:bt(_,l),sims:_}),p={method:M,wLow:d,wHigh:y,treatValue:b,controlValue:f};if(M==="mediate"){let R=De(),_=se=>je(e,s,n,{treat:r,mediator:m,treatValue:b,controlValue:f,covariates:{[o]:se},sims:t.sims??1e3,confLevel:l,robustSE:t.robustSE??!1}),q=_(d);Ve(R);let W=_(y),pe=W.dAvg.sims.map((se,yt)=>se-q.dAvg.sims[yt]),me=se=>({estimate:se.estimate,ci:se.ci,sims:se.sims});return{...p,indirectLow:me(q.dAvg),indirectHigh:me(W.dAvg),directLow:me(q.zAvg),directHigh:me(W.zAvg),totalLow:me(q.tau),totalHigh:me(W.tau),index:v(W.dAvg.estimate-q.dAvg.estimate,pe),low:q,high:W}}if(M!=="monteCarlo")throw new RangeError('method must be "monteCarlo" or "mediate"');let h=Math.trunc(t.nmc??2e4);if(!(h>=2))throw new RangeError("nmc must be at least 2");let T=t.robustSE?re(e,{type:"HC3"}):ne(e),w=t.robustSE?re(s,{type:"HC3"}):ne(s),g=(R,_)=>_.map(q=>{let W="family"in R?R.model.columnNames:R.coefNames;return R.coefficients[W.indexOf(q)]});de(T.vcov,"mediator"),de(w.vcov,"outcome");let A=Ne(h,g(e,T.names),T.vcov),S=Ne(h,g(s,w.names),w.vcov),C=g(e,T.names),$=g(s,w.names),O=(R,_,q)=>{let W=q===void 0?R.indexOf(_):[`${_}:${q}`,`${q}:${_}`].map(pe=>R.indexOf(pe)).find(pe=>pe>=0)??-1;if(q===void 0&&W<0)throw new RangeError(`a model has no coefficient '${_}'`);return W},j=O(T.names,r),V=O(T.names,r,o),x=O(w.names,m),F=O(w.names,m,o),D=O(w.names,r),Q=O(w.names,r,o),z=(R,_)=>_<0?0:R[_],U=b-f,le=(R,_,q)=>U*(z(R,j)+z(R,V)*q)*(z(_,x)+z(_,F)*q),N=(R,_)=>U*(z(R,D)+z(R,Q)*_),k=R=>Array.from({length:h},(_,q)=>R(q)),I=k(R=>le(A[R],S[R],d)),P=k(R=>le(A[R],S[R],y)),G=k(R=>N(S[R],d)),X=k(R=>N(S[R],y)),Y=le(C,$,d),J=le(C,$,y),H=N($,d),L=N($,y);return{...p,indirectLow:v(Y,I),indirectHigh:v(J,P),directLow:v(H,G),directHigh:v(L,X),totalLow:v(Y+H,I.map((R,_)=>R+G[_])),totalHigh:v(J+L,P.map((R,_)=>R+X[_])),index:v(J-Y,P.map((R,_)=>R-I[_]))}}export{Rt as balTab,Wt as johnsonNeyman,Mt as match,Je as matchWeights,je as mediate,Xt as mediationMonteCarlo,Jt as moderatedMediation,Kt as simSlopes,Bt as sobelTest,St as tableOneSmd,Ht as trimWeights,Dt as weightSummary,qt as weightit};
|
|
1
|
+
/*! rStats.js 1.19.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
|
|
2
|
+
import{a as Fe,b as Ne}from"./chunks/chunk-ILQ4VWSD.js";import{p as Pe,x as ne,y as re}from"./chunks/chunk-CEOSH3H2.js";import{a as Ie}from"./chunks/chunk-OTETSONJ.js";import{a as ae}from"./chunks/chunk-DXSVV47D.js";import{h as ke}from"./chunks/chunk-LSZTDKIB.js";import{a as ge}from"./chunks/chunk-YZ6SBFFG.js";import{b as Xe}from"./chunks/chunk-W4EITKLJ.js";import{f as Ue,h as ve,j as Be}from"./chunks/chunk-FELX2TZZ.js";import"./chunks/chunk-SAFH76DR.js";import"./chunks/chunk-MOYWWJP4.js";import"./chunks/chunk-U6RXYALO.js";import"./chunks/chunk-G4B2SQR6.js";import{a as Ge}from"./chunks/chunk-7D7FBLWD.js";import{d as te}from"./chunks/chunk-FCGTZ6BD.js";import"./chunks/chunk-QVE7V5UG.js";import"./chunks/chunk-NWNJEAKI.js";import{a as Ke}from"./chunks/chunk-5NW4WT4F.js";import{C as ue,w as He,x as Ce}from"./chunks/chunk-HPIZAWMT.js";import"./chunks/chunk-2S45NNTL.js";import"./chunks/chunk-ANFN3X2M.js";import{a as Re}from"./chunks/chunk-VNLSP22M.js";import{e as De,f as Ve,g as ze,m as We,n as we,o as be}from"./chunks/chunk-AS2XTRHH.js";import"./chunks/chunk-WWRKCRTZ.js";import"./chunks/chunk-MPBFXHXT.js";import"./chunks/chunk-XJMBX6A2.js";import"./chunks/chunk-BJ5WAL2C.js";import{t as qe,u as Z,v as fe}from"./chunks/chunk-CNJLPH6W.js";import{h as ee,k as B,l as Te}from"./chunks/chunk-LBU73UMS.js";import{l as K}from"./chunks/chunk-JXKHFSGK.js";function Ye(e){let s=0;for(let n of e)Math.abs(n)>s&&(s=Math.abs(n));return s>0&&Number.isFinite(s)?Math.floor(Math.log2(s)):0}function ie(e){let s=Ye(e),n=e.map(o=>ee(o,-s)),t=n[0]??0,r=n.map(o=>o-t),m=Ye(r);return{values:r.map(o=>ee(o,-m)),unitExp:s+m}}var Et=["estimand","M","caliper"];function Mt(e,s,n={}){K(n,Et,"match");let{estimand:t="ATT",M:r=1,caliper:m}=n,o=e.length;if(s.length!==o)throw new RangeError("length(Tr) != nrow(X)");if(t!=="ATT"&&t!=="ATE"&&t!=="ATC")throw new RangeError(`invalid 'estimand': ${String(t)}`);if(!Number.isInteger(r)||r<1)throw new RangeError("'M' must be a positive integer");if(m!==void 0&&!(m>0&&Number.isFinite(m)))throw new RangeError("'caliper' must be a positive number");let l=[];for(let g=0;g<o;g++){let A=e[g];if(A===!0||A===1)l.push(!0);else if(A===!1||A===0)l.push(!1);else throw typeof A=="number"&&Number.isNaN(A)?new RangeError("Match(): input includes NAs"):new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");if(!Number.isFinite(s[g]))throw new RangeError("Match(): input includes NAs")}if(!l.includes(!0)||!l.includes(!1))throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");let i=0;for(let g of s)i=Math.max(i,Math.abs(g));let c=i>0?Math.floor(Math.log2(i)):0,a=s.map(g=>ee(g,-c)),u=null,E=1/0;if(m!==void 0){let{values:g,unitExp:A}=ie(a),S=0;for(let O of g)S+=O;S/=o;let C=0;for(let O of g)C+=(O-S)*(O-S);let $=ee(Math.sqrt(C/o),A);E=m*$,u=ee(E,c)}let b=[new Array(o).fill(!1),new Array(o).fill(!1)],f=[],d=[],y=[],M=[],v=0,p=0;for(let g=0;g<o;g++){let A=l[g];if(A?t==="ATC":t==="ATT")continue;let S=b[A?0:1],C=[];for(let x=0;x<o;x++){if(l[x]===A)continue;let F=Math.abs(a[g]-a[x]);F>E||S[x]||C.push({j:x,d:F})}if(C.length<r){p++,y.push(g+1);continue}let O=C.map(x=>x.d).sort((x,F)=>x-F)[r-1],j=C.filter(x=>x.d<=O).map(x=>x.j),V;if(j.length===r)V=j;else{M.push(j.length),V=[],j=j.slice();for(let x=0;x<r;x++){let F=j.length,D=Math.min(F-1,Math.floor(F*(1-ze())));V.push(j[D]),j.splice(D,1)}V.sort((x,F)=>x-F)}for(let x of V)S[x]=!0,f.push((A?g:x)+1),d.push((A?x:g)+1);v++}let h=new Set([...f,...d]),T=u===null?[]:y.filter(g=>!h.has(g)),w=[];return f.length===0&&w.push("'Match' object contains no valid matches (probably because of the caliper or the exact option)."),{indexTreated:f,indexControl:d,weights:f.map(()=>1/r),indexDropped:T.length>0?T:null,caliper:m??null,ecaliper:u,nobs:o,wnobs:v,ndrops:p,estimand:t,M:r,tieSizes:M,warnings:w}}var At=["match","weightit","weights","estimand","levels","binary"],Tt=["factor"];function Je(e){let s=new Array(e.nobs).fill(0);return e.indexTreated.forEach((n,t)=>{s[n-1]+=e.weights[t],s[e.indexControl[t]-1]+=e.weights[t]}),s}function Nt(e,s){if(e===!0||e===1)return!0;if(e===!1||e===0)return!1;throw new RangeError(`'tr' must be 0 or 1 (element ${s+1})`)}function he(e,s,n,t){let r=0,m=0,o=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];r+=a,m+=a*a,o+=a*e[c]}let l=o/r,i=0;for(let c=0;c<e.length;c++){if(n[c]!==t)continue;let a=s===null?1:s[c];i+=a*(e[c]-l)*(e[c]-l)}return[l,i/(r-m/r)]}function Rt(e,s,n={}){K(n,At,"balTab");let{match:t,weightit:r,binary:m="raw",levels:o={}}=n;if(t!==void 0&&r!==void 0)throw new RangeError("give 'match' or 'weightit', not both");let l=t!==void 0?Je(t):r!==void 0?r.weights:n.weights,i=t?.estimand??r?.estimand??n.estimand??"ATT",c=new Set(t?.indexDropped??[]),a=t!==void 0&&t.caliper!==null,u=e.length,E=e.map(Nt);if(!E.includes(!0)||!E.includes(!1))throw new RangeError("'tr' must contain both groups");if(l!==void 0&&l.length!==u)throw new RangeError("'weights' must have the length of 'tr'");if(i==="ATO"&&l===void 0)throw new RangeError("estimand 'ATO' needs the weights");let b=[];r?.ps&&b.push(["prop.score",r.ps,"Distance"]);for(let[M,v]of Object.entries(s)){if(v.length!==u)throw new RangeError(`covariate '${M}' must have the length of 'tr'`);if(v.every(h=>typeof h=="number")){b.push([M,v,null]);continue}if(!v.every(h=>typeof h=="string"))throw new TypeError(`covariate '${M}' must be all numbers or all strings`);let p=o[M]??[...new Set(v)].sort(Re);if(v.some(h=>!p.includes(h)))throw new RangeError(`covariate '${M}' has values not among its levels`);for(let h of p.length===2?p.slice(1):p)b.push([`${M}_${h}`,v.map(T=>T===h?1:0),null])}let f=E.map(()=>!0),d=r!==void 0,y={rows:b.map(([M])=>M),type:[],diffUn:[],diffAdj:[],vRatioUn:[],vRatioAdj:[],observations:{rows:d?["Unadjusted","Adjusted"]:["All (ESS)","All (Unweighted)","Matched (ESS)","Matched (Unweighted)","Unmatched",...a?["Discarded"]:[]],control:[],treated:[]}};for(let[M,v,p]of b){if(v.some(D=>!Number.isFinite(D)))throw new RangeError(`covariate '${M}' has missing or infinite values`);let h=p===null&&new Set(v).size<=2&&v.every(D=>D===0||D===1),T=h?null:ie(v),w=T===null?v:T.values,[g,A]=he(w,null,E,!0),[S,C]=he(w,null,E,!1),$;if(i==="ATO"){let[D,Q]=he(w,l,f,!0);$=Math.sqrt(h?D*(1-D):Q)}else{let D=h?[g*(1-g),S*(1-S)]:[A,C];if($=Math.sqrt(i==="ATT"?D[0]:i==="ATC"?D[1]:(D[0]+D[1])/2),ee($,T?.unitExp??0)<Math.sqrt(Number.EPSILON)){let[Q,z]=he(w,null,f,!0);$=Math.sqrt(h?Q*(1-Q):z)}}let O=h&&m==="raw"?1:$;if(y.type.push(p??(h?"Binary":"Contin.")),y.diffUn.push(g===S?0:(g-S)/O),y.vRatioUn.push(h||C===0?NaN:A/C),l===void 0){y.diffAdj.push(NaN),y.vRatioAdj.push(NaN);continue}let[j,V]=he(w,l,E,!0),[x,F]=he(w,l,E,!1);y.diffAdj.push(j===x?0:(j-x)/O),y.vRatioAdj.push(h||F===0?NaN:V/F)}for(let M of[!1,!0]){let v=0,p=0,h=0,T=0,w=0;for(let S=0;S<u;S++){if(E[S]!==M||(v++,c.has(S+1)&&w++,l===void 0))continue;let C=l[S];p+=C,h+=C*C,C>0&&T++}let g=M?y.observations.treated:y.observations.control;if(d){g.push(v,p*p/h);continue}let A=l===void 0?[NaN,NaN,NaN]:[p*p/h,T,v-T-w];a&&A.push(w),g.push(v,v,...A)}return y}function St(e,s,n={}){K(n,Tt,"tableOneSmd");let{factor:t=!1}=n;if(e.length!==s.length)throw new RangeError("'x' and 'group' must have the same length");let r=[...new Set(s)].sort((f,d)=>f<d?-1:f>d?1:0);if(r.length!==2)throw new RangeError("'group' must have exactly two levels");let m=f=>f!==null&&!(typeof f=="number"&&Number.isNaN(f)),o=r.map(f=>e.filter((d,y)=>s[y]===f&&m(d)));if(!t){if(o.flat().some(p=>typeof p!="number"))throw new TypeError("'x' must be numeric unless factor: true");let f=ie(o.flat()).values,y=[f.slice(0,o[0].length),f.slice(o[0].length)].map(p=>{let h=p.reduce((T,w)=>T+w,0)/p.length;return[h,p.reduce((T,w)=>T+(w-h)*(w-h),0)/(p.length-1)]}),M=y[1][0]-y[0][0],v=Math.sqrt((y[0][1]+y[1][1])/2);return M===0?0:Math.abs(M)/v}let l=[...new Set(o.flat())].sort((f,d)=>typeof f=="number"&&typeof d=="number"?f-d:String(f)<String(d)?-1:String(f)>String(d)?1:0),i=o.map(f=>l.slice(1).map(d=>f.filter(y=>y===d).length/f.length)),c=i[1].map((f,d)=>f-i[0][d]);if(c.every(f=>f===0))return 0;let a=c.length,u=Array.from({length:a},(f,d)=>Array.from({length:a},(y,M)=>{let v=p=>d===M?p[d]*(1-p[d]):-p[d]*p[M];return(v(i[0])+v(i[1]))/2}));if(u.every(f=>f.every(d=>d===0)))return NaN;let E=Xe(u),b=0;for(let f=0;f<a;f++)for(let d=0;d<a;d++)b+=c[f]*E[f][d]*c[d];return Math.sqrt(b)}var Ot=["method","link","estimand","stabilize"],xt=["at","lower","treat"],oe=Number.EPSILON;function Ct(e){return e.map((s,n)=>{if(s===!0||s===1)return 1;if(s===!1||s===0)return 0;throw new RangeError(`'tr' must be 0 or 1 (element ${n+1})`)})}function kt(e,s){let n=[],t=[],r={};for(let[m,o]of Object.entries(e)){if(o.length!==s)throw new RangeError(`covariate '${m}' must have the length of 'tr'`);if(o.every(c=>typeof c=="number")){let c=o;if(c.some(a=>!Number.isFinite(a)))throw new RangeError(`covariate '${m}' has missing or infinite values`);n.push(m),t.push(c.slice());continue}if(!o.every(c=>typeof c=="string"))throw new TypeError(`covariate '${m}' must be all numbers or all strings`);let l=o,i=[...new Set(l)].sort(Re);r[m]=i;for(let c of i.slice(1))n.push(m+c),t.push(l.map(a=>a===c?1:0))}return{names:n,columns:t,factors:r}}function Qe(e){return e.map(s=>{let n=s.reduce((r,m)=>r+m,0)/s.length,t=s.reduce((r,m)=>Math.max(r,Math.abs(m-n)),0);return s.map(r=>t>0?(r-n)/t:0)})}function $t(e){let s=e[0]?.length??0,n=[new Array(s).fill(1/Math.sqrt(s))],t=[];for(let r of e){let m=Math.sqrt(r.reduce((i,c)=>i+c*c,0)),o=r.slice();for(let i=0;i<2;i++)for(let c of n){let a=o.reduce((u,E,b)=>u+E*c[b],0);for(let u=0;u<s;u++)o[u]-=a*c[u]}let l=Math.sqrt(o.reduce((i,c)=>i+c*c,0));l>1e-7*m&&(n.push(o.map(i=>i/l)),t.push(r))}return t}function st(e,s){let n=s.length,t=e.map((o,l)=>[...o,s[l]]),r=0;for(let o of e)for(let l of o)r=Math.max(r,Math.abs(l));for(let o=0;o<n;o++){let l=o;for(let i=o+1;i<n;i++)Math.abs(t[i][o])>Math.abs(t[l][o])&&(l=i);if(!(Math.abs(t[l][o])>1e-13*r))return null;[t[o],t[l]]=[t[l],t[o]];for(let i=o+1;i<n;i++){let c=t[i][o]/t[o][o];if(c!==0)for(let a=o;a<=n;a++)t[i][a]-=c*t[o][a]}}let m=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let l=t[o][n];for(let i=o+1;i<n;i++)l-=t[o][i]*m[i];m[o]=l/t[o][o]}return m}function $e(e,s){return Array.from({length:s},(n,t)=>[1,...e.map(r=>r[t])])}function Ze(e,s,n){let t=n.length,r=new Array(t).fill(0);r[0]=Math.log(n[0]/s.length);let m=c=>{let a=0;for(let u of s)a+=Math.exp(e[u].reduce((E,b,f)=>E+b*c[f],0));return a-n.reduce((u,E,b)=>u+E*c[b],0)},o=m(r),l=!1,i=1e-13*Math.max(1,Math.abs(n[0]));for(let c=0;c<200;c++){let a=n.map(p=>-p),u=Array.from({length:t},()=>new Array(t).fill(0));for(let p of s){let h=e[p],T=Math.exp(h.reduce((w,g,A)=>w+g*r[A],0));for(let w=0;w<t;w++){a[w]+=T*h[w];for(let g=0;g<=w;g++)u[w][g]+=T*h[w]*h[g]}}for(let p=0;p<t;p++)for(let h=p+1;h<t;h++)u[p][h]=u[h][p];let E=Math.max(...a.map(Math.abs));if(E<=i){l=!0;break}let b=st(u,a.map(p=>-p));if(b===null||b.some(p=>!Number.isFinite(p)))break;let f=1e-12*(Math.abs(o)+1),d=1,y=r.map((p,h)=>p+b[h]),M=m(y);for(;!(M<=o+f)&&d>1e-10;)d/=2,y=r.map((p,h)=>p+d*b[h]),M=m(y);if(!(M<=o+f))break;let v=b.some((p,h)=>Math.abs(d*p)>1e-15*Math.max(1,Math.abs(r[h])));if(r.splice(0,t,...y),o=M,!v){l=E<=1e-9*Math.max(1,Math.abs(n[0]));break}}return{eta:e.map(c=>c.reduce((a,u,E)=>a+u*r[E],0)),converged:l}}var Lt={logit:{p:e=>te(e),q:e=>te(-e),d:e=>te(e)*te(-e)},probit:{p:e=>Z(e),q:e=>Z(-e),d:e=>qe(e)}};function _t(e,s,n,t,r){let m=s.length,o=r.length,l=r.slice(),i=d=>{let y=new Array(o).fill(0),M=Array.from({length:o},()=>new Array(o).fill(0));for(let v=0;v<m;v++){let p=e[v],h=p.reduce(($,O,j)=>$+O*d[j],0),T=t.p(h),w=t.q(h),g=t.d(h),A=s[v],S,C;n==="ATE"?(S=A?1/T:-1/w,C=A?-g/(T*T):-g/(w*w)):n==="ATT"?(S=A?1:-T/w,C=A?0:-g/(w*w)):n==="ATC"?(S=A?w/T:-1,C=A?-g/(T*T):0):(S=A?w:-T,C=-g);for(let $=0;$<o;$++){y[$]+=S*p[$];for(let O=0;O<o;O++)M[$][O]+=C*p[$]*p[O]}}return{g:y,J:M}},c=d=>d.reduce((y,M)=>y+M*M,0),{g:a,J:u}=i(l),E=c(a),b=!1,f=1e-12*m;for(let d=0;d<200;d++){if(Math.max(...a.map(Math.abs))<=f){b=!0;break}let y=st(u,a.map(T=>-T));if(y===null||y.some(T=>!Number.isFinite(T)))break;let M=1,v=l.map((T,w)=>T+y[w]),p=i(v),h=c(p.g);for(;!(h<E)&&M>1e-10;)M/=2,v=l.map((T,w)=>T+M*y[w]),p=i(v),h=c(p.g);if(!(h<E)){b=Math.max(...a.map(Math.abs))<=1e-8*m;break}l=v,a=p.g,u=p.J,E=h}return{eta:e.map(d=>d.reduce((y,M,v)=>y+M*l[v],0)),converged:b}}function et(e,s,n,t){switch(e){case"ATE":return s?1/n:1/t;case"ATT":return s?1:n/t;case"ATC":return s?t/n:1;default:return s?t:n}}var jt={glm:"glm.fit: algorithm did not converge",cbps:"The covariate balancing conditions could not be solved, so the covariates will not be exactly balanced.",ipt:"The optimization failed to converge; consider using fewer covariates or a different link function.",ebal:"The estimated weights do not balance the covariates, indicating the optimization arrived at a degenerate solution. Try decreasing the number of variables supplied to the optimization."},tt={cbps:"covariate balancing propensity score weighting",ipt:"inverse probability tilting",ebal:"entropy balancing"};function qt(e,s,n={}){K(n,Ot,"weightit");let{method:t="glm",estimand:r="ATE",stabilize:m=!1}=n,o=t==="ps"?"glm":t;if(!["glm","cbps","ipt","ebal"].includes(o))throw new RangeError(`unknown method '${String(t)}'`);if(!["ATE","ATT","ATC","ATO"].includes(r))throw new RangeError(`unknown estimand '${String(r)}'`);let l=o==="ebal"?null:n.link??"logit";if(l!==null&&!{glm:["logit","probit","cauchit","cloglog"],cbps:["logit","probit"],ipt:["logit"]}[o].includes(l))throw new RangeError(`link '${l}' is not available for method '${o}'`);if((o==="ipt"||o==="ebal")&&r==="ATO")throw new RangeError(`"ATO" is not an allowable estimand for ${tt[o]} with a binary treatment. Only "ATE", "ATT", and "ATC" are allowed.`);let c=[];if(m&&o==="glm"&&r!=="ATE")throw new RangeError('`stabilize` can only be supplied when `estimand = "ATE"`.');m&&o!=="glm"&&c.push(`\`stabilize\` cannot be used with ${tt[o]} and will be ignored.`);let a=Ct(e),u=a.length;if(!a.includes(0)||!a.includes(1))throw new RangeError("The treatment must have at least two unique values.");let{names:E,columns:b}=kt(s,u);if(b.length===0)throw new RangeError("'covariates' must have at least one column");let f=$t(b.map(w=>ie(w).values)),d=a.flatMap((w,g)=>w?[g]:[]),y=a.flatMap((w,g)=>w?[]:[g]),M=a.map((w,g)=>g),v=r==="ATT"?1:r==="ATC"?0:null,p=null,h,T=!0;if(o==="glm"){let w=be(()=>ve($e(f,u).map(g=>g.slice(1)),a,{family:"binomial",link:l}));T=w.converged,p=w.fittedValues.map((g,A)=>l==="logit"&&Math.abs(w.linearPredictors[A])>30?w.linearPredictors[A]>0?1-oe:oe:Math.min(Math.max(g,oe),1-oe)),h=a.map((g,A)=>et(r,g,p[A],1-p[A])),p.some(g=>g<=10*oe||g>=1-10*oe)&&c.push("Propensity scores numerically equal to 0 or 1 were estimated, indicating perfect separation. These may yield problems with inference. See `?method_glm` (`?WeightIt::method_glm()`) for details.")}else if(o==="cbps"){let w=Qe(f),g=$e(w,u),A=be(()=>ve(g.map(O=>O.slice(1)),a,{family:"binomial",link:l})).coefficients.map(O=>Number.isFinite(O)?O:0),S=Lt[l],C=_t(g,a,r,S,A);T=C.converged;let $=O=>Math.min(Math.max(O,oe),1-oe);p=C.eta.map(O=>$(S.p(O))),h=a.map((O,j)=>et(r,O,p[j],$(S.q(C.eta[j]))))}else{let w=Qe(f),g=$e(w,u),A=j=>g[0].map((V,x)=>j.reduce((F,D)=>F+g[D][x],0)),S={C:r!=="ATC",T:r!=="ATT"},C=o==="ebal"&&r==="ATE"?{C:A(M),T:A(M)}:{C:A(d),T:A(y)},$=S.C?Ze(g,y,C.C):null,O=S.T?Ze(g,d,C.T):null;if(T=($?.converged??!0)&&(O?.converged??!0),o==="ebal")h=a.map((j,V)=>j?O?Math.exp(O.eta[V]):1:$?Math.exp($.eta[V]):1);else{let j=r==="ATE"?1:0;h=a.map((V,x)=>V?O?j+Math.exp(O.eta[x]):1:$?j+Math.exp($.eta[x]):1),p=a.map((V,x)=>r==="ATT"?te($.eta[x]):r==="ATC"?te(-O.eta[x]):V?te(-O.eta[x]):te($.eta[x]))}}if(T||c.push(jt[o]),m&&o==="glm"){let w=[y.length/u,d.length/u];h=h.map((g,A)=>g*w[a[A]])}return h.every(w=>Math.abs(w-1)<Math.sqrt(oe))&&c.push("All weights are 1, possibly indicating an estimation failure."),we("weightit",{weights:h,ps:p,treat:a,estimand:r,method:o,link:l,stabilized:m&&o==="glm",focal:v,columnNames:E,converged:T,warnings:c})}function nt(e,s,n,t){let r=e.slice();if(s.length===0)return r;let m=s.map(i=>e[i]),o,l;if(n<1){let i=n<.5?1-n:n;o=ae(m,i,{type:3}),l=ae(m,1-i,{type:3})}else{if(!Number.isInteger(n))throw new RangeError("'at' must be below 1 or a whole number");if(n>=m.length)return null;let i=n>m.length/2?m.length-n:n,c=m.slice().sort((a,u)=>a-u);o=c[c.length-1-i],l=c[i]}for(let i of s)e[i]>o&&(r[i]=o),t&&e[i]<l&&(r[i]=l);return r}var ot=e=>`\`at\` must be less than ${e}, the number of units. Weights will not be trimmed.`;function Ht(e,s){K(s,xt,"trimWeights");let{at:n,lower:t=!1}=s;if(!(n>0)||!Number.isFinite(n))throw new RangeError("'at' must be a positive number");if(Array.isArray(e)||ArrayBuffer.isView(e)){let l=Array.from(e);if(s.treat!==void 0&&s.treat.length!==l.length)throw new RangeError("'treat' must have the length of 'w'");let i=nt(l,l.map((c,a)=>a),n,t);return i===null?(We("trimWeights",[ot(l.length)]),l):i}let r=e,m=r.treat.flatMap((l,i)=>r.focal===null||l!==r.focal?[i]:[]),o=nt(r.weights,m,n,t);return o===null?we("trimWeights",{...r,weights:r.weights.slice(),warnings:[ot(m.length)]}):{...r,weights:o,warnings:r.warnings.slice()}}function rt(e,s){let n=s.map(a=>e[a]),t=n.length,r=0,m=0;for(let a of n)r+=a,m+=a*a;let o=r/t,l=n.reduce((a,u)=>a+(u-o)*(u-o),0),i=n.map(a=>o>0?a/o:NaN),c=n.map((a,u)=>u).sort((a,u)=>n[u]-n[a]||a-u).slice(0,5).reverse();return{range:[Math.min(...n),Math.max(...n)],top:{index:c.map(a=>s[a]+1),weights:c.map(a=>n[a])},mean:o,coefOfVar:Math.sqrt(l/(t-1))/o,scaledMad:i.reduce((a,u)=>a+Math.abs(u-1),0)/t,negativeEntropy:i.reduce((a,u)=>a+(Number.isNaN(u)?NaN:u>0?u*Math.log(u):0),0)/t,numZeros:n.filter(a=>Math.abs(a)<1e-10).length,n:t,ess:r*r/m}}function Dt(e){let s=e.treat.flatMap((t,r)=>t?[r]:[]),n=e.treat.flatMap((t,r)=>t?[]:[r]);return{treated:rt(e.weights,s),control:rt(e.weights,n),stabilized:e.stabilized}}var Vt=new Set(["treat","mediator","treatValue","controlValue","covariates","sims","boot","bootCiType","confLevel","robustSE"]);function at(e,s,n){let t=Ue(e);if(t===void 0||typeof e.formula!="string")throw new TypeError(`the ${n} model must be a formula fit of lm or glm`);if(t.weights!==void 0||t.offset!==void 0)throw new RangeError(`weights and offsets are not supported (the ${n} model)`);let r="family"in e,m=a=>a;if(r){let a=e;if(a.family==="binomial"&&(a.link==="logit"||a.link==="probit"))m=Be(a).linkinv;else if(!(a.family==="gaussian"&&a.link==="identity"))throw new RangeError(`the ${n} model's family is not supported (binomial with logit or probit, or gaussian)`)}if(e.coefficients.some(a=>Number.isNaN(a)))throw new RangeError(`the ${n} model has aliased coefficients`);let o=e.formula,l=Ge(Ke(o,!1,!1,!0),s,{...t.contrasts===void 0?{}:{contrasts:t.contrasts},...t.levels===void 0?{}:{levels:t.levels},dropUnusedLevels:!0,anyResponse:!0}),i=r?e.model.rows:e.rows,c=r?e.model.columnNames:e.coefNames;if(l.frame.rows.length!==i.length||l.frame.rows.some((a,u)=>a!==i[u])||l.colNames.join("\0")!==c.join("\0"))throw new RangeError(`the data do not give the ${n} model's rows and columns (pass the data it was fitted on)`);return{fit:e,isGlm:r,formula:o,options:t,coef:e.coefficients.slice(),names:c,linkinv:m,d:l,rows:i}}function ye(e,s,n,t){let r=e.d.terms.variables.indexOf(s);if(r<0){if(t)throw new RangeError(`'${s}' is not a variable of the ${n} model`);return-1}if(e.d.frame.variables[r].kind!=="numeric")throw new RangeError(`'${s}' must be numeric in the ${n} model`);return r}function ut(e,s,n){let t=e.d.frame.variables.map((r,m)=>{let o=s.get(m);return o===void 0?r:{kind:"numeric",values:typeof o=="number"?new Array(n).fill(o):o.slice()}});return e.d.rowsOf(t,n)}var ce=(e,s)=>{let n=0;for(let t=0;t<e.length;t++)n+=e[t]*s[t];return n};function it(e,s,n,t){let r=e.length,m=2**-1022,o=Number.MAX_VALUE;if(s.some((a,u)=>a.some(E=>!Number.isFinite(E))||!(a[u]>=m&&a[u]<=o)))throw new RangeError(`the ${t} model's coefficient covariance is out of the double range (rescale the variables, or use boot: true)`);let l=Fe(s),i=ue(n*r),c=[];for(let a=0;a<n;a++){let u=[];for(let E=0;E<r;E++){let b=0;for(let f=0;f<r;f++)b+=i[a*r+f]*l[f][E];u.push(e[E]+b)}c.push(u)}return c}function Oe(e,s){let n=new Map(e.mCov);return n.set(e.mTreat,s),ut(e.m,n,e.n)}function Me(e,s,n){let t=new Map(e.yCov);return t.set(e.yTreat,s),t.set(e.yMed,n),ut(e.y,t,e.n)}function Se(e,s,n,t){return Me(e,s,n).map(r=>e.y.linkinv(ce(r,t)))}var Ee=(e,s)=>B(e.map((n,t)=>n-s[t]));function ht(e,s,n,t){if(xe(e.y)){let i=Me(e,e.t0,s),c=Me(e,e.t0,n),a=Me(e,e.t1,s),u=Me(e,e.t1,n),E=(b,f)=>B(b.map((d,y)=>{let M=0;for(let v=0;v<d.length;v++)M+=(d[v]-f[y][v])*t[v];return M}));return[E(i,c),E(a,u),E(u,c),E(a,i),E(a,c)]}let r=Se(e,e.t0,s,t),m=Se(e,e.t0,n,t),o=Se(e,e.t1,s,t),l=Se(e,e.t1,n,t);return[Ee(r,m),Ee(o,l),Ee(l,m),Ee(o,r),Ee(o,m)]}function Le(e,s,n,t){let r=e.n,m=Oe(e,e.t1).map(c=>ce(c,s)),o=Oe(e,e.t0).map(c=>ce(c,s)),l,i;if(xe(e.m)){let c=ue(r,{sd:n});l=m.map((a,u)=>a+c[u]),i=o.map((a,u)=>a+c[u])}else l=m.map(c=>ge(1,e.m.linkinv(c))),i=o.map(c=>ge(1,e.m.linkinv(c)));return ht(e,l,i,t)}var xe=e=>!e.isGlm||e.fit.family==="gaussian",_e=e=>e.isGlm?Math.sqrt(zt(e.fit)):e.fit.sigma;function zt(e){let s=0;for(let n=0;n<e.residuals.length;n++)s+=e.weights[n]*e.residuals[n]**2;return s/e.dfResidual}var ct=(e,s,n)=>{let t=ae(e,[s,n],{type:7});return[t[0],t[1]]};function je(e,s,n,t){K(t,Vt,"mediate");let{treat:r,mediator:m}=t;if(typeof r!="string"||typeof m!="string")throw new TypeError("'treat' and 'mediator' are required");let o=t.treatValue??1,l=t.controlValue??0;if(!Number.isFinite(o)||!Number.isFinite(l))throw new RangeError("treatValue and controlValue must be finite");let i=Math.trunc(t.sims??1e3),c=t.boot??!1,a=t.bootCiType??"perc";if(a!=="perc"&&a!=="bca")throw new RangeError('bootCiType must be "perc" or "bca"');let u=t.confLevel??.95;if(!(u>0&&u<1))throw new RangeError("confLevel must be in (0, 1)");let E=t.robustSE??!1;if(!(i>=2))throw new RangeError("sims must be at least 2");let b=[];c&&E&&b.push("'robustSE' is ignored for nonparametric bootstrap");let f=at(e,n,"mediator"),d=at(s,n,"outcome");if(!xe(f)&&e.family!=="binomial")throw new RangeError("unsupported mediator model");if(f.d.terms.variables[0]!==m)throw new RangeError(`the mediator model's response must be '${m}'`);if(f.rows.length!==d.rows.length||f.rows.some((N,k)=>N!==d.rows[k]))throw new RangeError("number of observations do not match between mediator and outcome models");let y=f.rows.length,M=Object.entries(t.covariates??{});for(let[,N]of M)if(!Number.isFinite(N))throw new RangeError("covariate values must be finite");let v={m:f,y:d,treat:r,mediator:m,t1:o,t0:l,n:y,mTreat:ye(f,r,"mediator",!0),yTreat:ye(d,r,"outcome",!0),yMed:ye(d,m,"outcome",!0),mCov:M.map(([N,k])=>[ye(f,N,"mediator",!1),k]).filter(([N])=>N>=0),yCov:M.map(([N,k])=>[ye(d,N,"outcome",!1),k]).filter(([N])=>N>=0)};if(M.some(([N])=>!f.d.terms.variables.includes(N)&&!d.d.terms.variables.includes(N)))throw new RangeError("covariates must be variables of the models");let p=xe(f),h,T;if(c){let N=Ie(y,{size:y*i,replace:!0}),k=[...new Set([...f.d.terms.variables,...d.d.terms.variables])],I=p?_e(f):NaN;Le(v,f.coef,I,d.coef),h=[];for(let P=0;P<i;P++){let G=Array.from({length:y},(H,L)=>f.rows[N[P+L*i]]),X=Object.fromEntries(k.map(H=>{let L=n[H];return[H,G.map(R=>L[R])]})),Y=lt(f,X),J=lt(d,X);h.push(Le(v,ft(Y,f,b),p?_e({...f,fit:Y,isGlm:"family"in Y}):NaN,ft(J,d,b)))}T=Le(v,f.coef,I,d.coef)}else{let N=E?re(e,{type:"HC3"}).vcov:ne(e).vcov,k=E?re(s,{type:"HC3"}).vcov:ne(s).vcov,I=it(f.coef,N,i,"mediator"),P=it(d.coef,k,i,"outcome"),G=Oe(v,o),X=Oe(v,l),Y=Array.from({length:i},()=>new Array(y)),J=Array.from({length:i},()=>new Array(y));if(p){let H=ue(i*y,{sd:_e(f)});for(let L=0;L<y;L++)for(let R=0;R<i;R++)Y[R][L]=ce(G[L],I[R])+H[L*i+R],J[R][L]=ce(X[L],I[R])+H[L*i+R]}else{for(let H=0;H<y;H++)for(let L=0;L<i;L++)Y[L][H]=ge(1,f.linkinv(ce(G[H],I[L])));for(let H=0;H<y;H++)for(let L=0;L<i;L++)J[L][H]=ge(1,f.linkinv(ce(X[H],I[L])))}h=I.map((H,L)=>ht(v,Y[L],J[L],P[L]))}let w=N=>h.map(k=>k[N]),g=w(0),A=w(1),S=w(2),C=w(3),$=w(4),O=g.map((N,k)=>N/$[k]),j=A.map((N,k)=>N/$[k]),V=g.map((N,k)=>(N+A[k])/2),x=S.map((N,k)=>(N+C[k])/2),F=O.map((N,k)=>(N+j[k])/2),D=(1-u)/2,Q=(1+u)/2,z=(N,k)=>{let I;if(c&&a==="bca"){let X=B(N),Y=0,J=0,H=0;for(let q of N){let W=X-q;Y+=W*W,J+=W*W*W,q<X&&H++}let L=J/(6*Y**1.5),R=fe(H/N.length),_=q=>Z(R+(R+q)/(1-L*(R+q)));I=ct(N,_(fe(D)),_(fe(Q)))}else I=ct(N,D,Q);let P=0,G=0;for(let X of N)X>0?P++:X<0&&G++;return{estimate:k,ci:I,p:2*Math.min(P/N.length,G/N.length),sims:N}},U;if(T===void 0){let N=ke(O),k=ke(j);U=[B(g),B(A),B(S),B(C),B($),N,k,B(V),B(x),(N+k)/2]}else{let[N,k,I,P,G]=T;U=[N,k,I,P,G,N/G,k/G,(N+k)/2,(I+P)/2,(N/G+k/G)/2]}let le=d.d.terms.termLabels.some(N=>{let k=N.split(":");return k.length>1&&k.includes(r)&&k.includes(m)});return we("mediate",{d0:z(g,U[0]),d1:z(A,U[1]),z0:z(S,U[2]),z1:z(C,U[3]),tau:z($,U[4]),n0:z(O,U[5]),n1:z(j,U[6]),dAvg:z(V,U[7]),zAvg:z(x,U[8]),nAvg:z(F,U[9]),treatValue:o,controlValue:l,nobs:y,sims:i,boot:c,bootCiType:a,confLevel:u,robustSE:E&&!c,INT:le,warnings:b})}function lt(e,s){let n={...e.options};return be(()=>e.isGlm?ve(e.formula,s,n):Pe(e.formula,s,n))}var mt='prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';function ft(e,s,n){let t="family"in e?e.model.columnNames:e.coefNames;return s.names.map(r=>{let m=t.indexOf(r);return m<0||Number.isNaN(e.coefficients[m])?(n.includes(mt)||n.push(mt),0):e.coefficients[m]})}var It=["pred","modx","modxValues","johnsonNeyman","jnAlpha","ciWidth","robust"],Ft=["pred","modx","alpha","robust"];function dt(e,s,n,t,r){if(typeof n!="string"||typeof t!="string")throw new TypeError("'pred' and 'modx' are required");if(r!==!1&&r!=="HC3")throw new RangeError('robust must be false or "HC3"');let m="family"in e,o=m?e.model.columnNames:e.coefNames;if(o===void 0)throw new TypeError("the model must be a formula fit of lm or glm");if(m&&e.family!=="binomial"&&e.family!=="gaussian")throw new RangeError("the model's family is not supported (binomial or gaussian)");let l=[`${n}:${t}`,`${t}:${n}`].find(d=>o.includes(d));if(!o.includes(n)||l===void 0)throw new RangeError(`the model has no coefficients '${n}' and '${n}:${t}'`);let i=r==="HC3"?re(e,{type:"HC3"}):ne(e),c=i.names.indexOf(n),a=i.names.indexOf(l);if(c<0||a<0)throw new RangeError("the predictor's or the interaction's coefficient is aliased");let u=e.coefficients,E=m?e.model.rows:e.rows,b=s[t];if(b===void 0)throw new RangeError(`object '${t}' not found`);let f=E.map(d=>Number(b[d]));if(f.some(d=>!Number.isFinite(d)))throw new RangeError(`'${t}' must be numeric`);return{b1:u[o.indexOf(n)],b3:u[o.indexOf(l)],v11:i.vcov[c][c],v13:i.vcov[c][a],v33:i.vcov[a][a],df:e.dfResidual,isGlm:m&&e.family==="binomial",w:f}}function pt(e,s){if(!(s>0&&s<1))throw new RangeError("alpha must be in (0, 1)");let n=Ce(1-s/2,e.df),t=n*n,r=2**-1022,m=Number.MAX_VALUE;if(![e.v11,e.v33].every(A=>A>=r&&A<=m)||!Number.isFinite(e.v13))throw new RangeError("the model's coefficient covariance is out of the double range (rescale the variables)");let o=2**Math.round(Math.log2(e.v11)/2),l=2**Math.round((Math.log2(e.v11)-Math.log2(e.v33))/2),i=e.b1/o,c=e.b3/o*l,a=e.v11/o/o,u=e.v13/o/o*l,E=e.v33/o/o*l*l,b=c*c-t*E,f=2*(i*c-t*u),d=i*i-t*a,y=f*f-4*b*d,M=Math.min(...e.w),v=Math.max(...e.w),p=[M,v],h,T=!1;if(!(y>=0))h=[-1/0,1/0],T=!0;else{let A=Math.sqrt(y),S=(-f-Math.sign(f||1)*A)/(2*b),C=S===0?(-f+Math.sign(f||1)*A)/(2*b):d/(b*S);h=S<=C?[S*l,C*l]:[C*l,S*l]}let w=!T&&b<0,g=!(h[0]>M&&h[0]<v)&&!(h[1]>M&&h[1]<v);return{bounds:h,inside:w,failed:T,allSig:g,modrange:p,alpha:s}}function Wt(e,s,n){return K(n,Ft,"johnsonNeyman"),pt(dt(e,s,n.pred,n.modx,n.robust??!1),n.alpha??.05)}function Kt(e,s,n){K(n,It,"simSlopes");let t=dt(e,s,n.pred,n.modx,n.robust??!1),r=n.ciWidth??.95;if(!(r>0&&r<1))throw new RangeError("ciWidth must be in (0, 1)");let m=n.modxValues??"mean-plus-minus",o;if(m==="mean-plus-minus"){let b=B(t.w),f=Math.sqrt(Te(t.w));o=[b-f,b,b+f]}else if(Array.isArray(m)&&m.every(b=>Number.isFinite(b)))o=[...m];else throw new RangeError('modxValues must be "mean-plus-minus" or finite numbers');let l=t.isGlm?fe((1+r)/2):Ce((1+r)/2,t.df),i=o.map(b=>t.b1+t.b3*b),c=o.map(b=>Math.sqrt(t.v11+2*b*t.v13+b*b*t.v33)),a=i.map((b,f)=>b/c[f]),u=a.map(b=>2*(t.isGlm?Z(-Math.abs(b)):He(-Math.abs(b),t.df))),E={values:o,estimate:i,se:c,lower:i.map((b,f)=>b-l*c[f]),upper:i.map((b,f)=>b+l*c[f]),statistic:a,statisticName:t.isGlm?"z":"t",p:u};return(n.johnsonNeyman??!0)&&(E.jn=pt(t,n.jnAlpha??.05)),E}var Gt=["treat","mediator"],Ut=["nmc","confLevel","treat","mediator"],Pt=new Set(["moderator","treatValue","controlValue","wLow","wHigh","method","nmc","sims","confLevel","robustSE","treat","mediator"]);function de(e,s){let n=22250738585072014e-324,t=Number.MAX_VALUE;if(e.some((r,m)=>r.some(o=>!Number.isFinite(o))||!(r[m]>=n&&r[m]<=t)))throw new RangeError(`the ${s} model's coefficient covariance is out of the double range (rescale the variables)`)}function Ae(e,s,n){let t=ne(e),r=t.names.indexOf(s);if(r<0)throw new RangeError(`the ${n} model has no coefficient '${s}'`);let m="family"in e?e.model.columnNames:e.coefNames;return{value:e.coefficients[m.indexOf(s)],v:t.vcov[r][r],names:t.names,vcov:t.vcov}}function Bt(e,s,n){K(n,Gt,"sobelTest");let t=Ae(e,n.treat,"mediator"),r=Ae(s,n.mediator,"outcome");de([[t.v]],"mediator"),de([[r.v]],"outcome");let m=t.value,o=r.value,l=Math.sqrt(t.v),i=Math.sqrt(r.v),c=m*o,a=Math.hypot(o*l,m*i),u=c/a;return{a:m,sa:l,b:o,sb:i,ab:c,se:a,z:u,p:2*Z(Math.abs(u),{lowerTail:!1})}}var bt=(e,s)=>{let n=1-s,t=ae(e,[n/2,1-n/2],{type:7});return[t[0],t[1]]};function vt(e){if(!(e>0&&e<1))throw new RangeError("confLevel must be in (0, 1)")}function Xt(e,s,n){K(n,Ut,"mediationMonteCarlo");let t=Math.trunc(n.nmc??2e4),r=n.confLevel??.95;if(vt(r),!(t>=2))throw new RangeError("nmc must be at least 2");let m=Ae(e,n.treat,"mediator"),o=Ae(s,n.mediator,"outcome"),l=Ae(s,n.treat,"outcome"),i=o.names.indexOf(n.mediator),c=o.names.indexOf(n.treat);de([[m.v]],"mediator"),de([[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]],"outcome");let a=ue(t,{mean:m.value,sd:Math.sqrt(m.v)}),u=Ne(t,[o.value,l.value],[[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]]),E=a.map((p,h)=>p*u[h][0]),b=u.map(p=>p[1]),f=E.map((p,h)=>p+b[h]),d=E.map((p,h)=>p/f[h]),y=m.value*o.value,M=l.value,v=(p,h)=>({estimate:p,ci:bt(h,r),sims:h});return{indirect:v(y,E),direct:v(M,b),total:v(y+M,f),proportion:v(y/(y+M),d)}}function gt(e,s,n){let t=e[n];if(t===void 0)throw new RangeError(`object '${n}' not found`);let r=s.map(i=>Number(t[i]));if(r.some(i=>!Number.isFinite(i)))throw new RangeError(`'${n}' must be numeric`);let m=[...new Set(r)].sort((i,c)=>i-c);if(m.length===2)return[m[0],m[1]];let o=B(r),l=Math.sqrt(Te(r));return[o-l,o+l]}var wt=e=>!("family"in e)||e.family==="gaussian",Yt=e=>"family"in e?e.model.rows:e.rows;function Jt(e,s,n,t){K(t,Pt,"moderatedMediation");let{treat:r,mediator:m,moderator:o}=t;if(typeof r!="string"||typeof m!="string"||typeof o!="string")throw new TypeError("'treat', 'mediator' and 'moderator' are required");let l=t.confLevel??.95;vt(l);let i=Yt(e),[c,a]=gt(n,i,r),[u,E]=gt(n,i,o),b=t.treatValue??a,f=t.controlValue??c,d=t.wLow??u,y=t.wHigh??E,M=t.method??(wt(e)&&wt(s)?"monteCarlo":"mediate"),v=(R,_)=>({estimate:R,ci:bt(_,l),sims:_}),p={method:M,wLow:d,wHigh:y,treatValue:b,controlValue:f};if(M==="mediate"){let R=De(),_=se=>je(e,s,n,{treat:r,mediator:m,treatValue:b,controlValue:f,covariates:{[o]:se},sims:t.sims??1e3,confLevel:l,robustSE:t.robustSE??!1}),q=_(d);Ve(R);let W=_(y),pe=W.dAvg.sims.map((se,yt)=>se-q.dAvg.sims[yt]),me=se=>({estimate:se.estimate,ci:se.ci,sims:se.sims});return{...p,indirectLow:me(q.dAvg),indirectHigh:me(W.dAvg),directLow:me(q.zAvg),directHigh:me(W.zAvg),totalLow:me(q.tau),totalHigh:me(W.tau),index:v(W.dAvg.estimate-q.dAvg.estimate,pe),low:q,high:W}}if(M!=="monteCarlo")throw new RangeError('method must be "monteCarlo" or "mediate"');let h=Math.trunc(t.nmc??2e4);if(!(h>=2))throw new RangeError("nmc must be at least 2");let T=t.robustSE?re(e,{type:"HC3"}):ne(e),w=t.robustSE?re(s,{type:"HC3"}):ne(s),g=(R,_)=>_.map(q=>{let W="family"in R?R.model.columnNames:R.coefNames;return R.coefficients[W.indexOf(q)]});de(T.vcov,"mediator"),de(w.vcov,"outcome");let A=Ne(h,g(e,T.names),T.vcov),S=Ne(h,g(s,w.names),w.vcov),C=g(e,T.names),$=g(s,w.names),O=(R,_,q)=>{let W=q===void 0?R.indexOf(_):[`${_}:${q}`,`${q}:${_}`].map(pe=>R.indexOf(pe)).find(pe=>pe>=0)??-1;if(q===void 0&&W<0)throw new RangeError(`a model has no coefficient '${_}'`);return W},j=O(T.names,r),V=O(T.names,r,o),x=O(w.names,m),F=O(w.names,m,o),D=O(w.names,r),Q=O(w.names,r,o),z=(R,_)=>_<0?0:R[_],U=b-f,le=(R,_,q)=>U*(z(R,j)+z(R,V)*q)*(z(_,x)+z(_,F)*q),N=(R,_)=>U*(z(R,D)+z(R,Q)*_),k=R=>Array.from({length:h},(_,q)=>R(q)),I=k(R=>le(A[R],S[R],d)),P=k(R=>le(A[R],S[R],y)),G=k(R=>N(S[R],d)),X=k(R=>N(S[R],y)),Y=le(C,$,d),J=le(C,$,y),H=N($,d),L=N($,y);return{...p,indirectLow:v(Y,I),indirectHigh:v(J,P),directLow:v(H,G),directHigh:v(L,X),totalLow:v(Y+H,I.map((R,_)=>R+G[_])),totalHigh:v(J+L,P.map((R,_)=>R+X[_])),index:v(J-Y,P.map((R,_)=>R-I[_]))}}export{Rt as balTab,Wt as johnsonNeyman,Mt as match,Je as matchWeights,je as mediate,Xt as mediationMonteCarlo,Jt as moderatedMediation,Kt as simSlopes,Bt as sobelTest,St as tableOneSmd,Ht as trimWeights,Dt as weightSummary,qt as weightit};
|