@numero-uno-jpn/rstats 1.17.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.
Files changed (97) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.ja.md +7 -7
  3. package/README.md +7 -7
  4. package/dist/causal/mediationProcedures.js +18 -1
  5. package/dist/causal/moderation.js +11 -2
  6. package/dist/causal.js +2 -2
  7. package/dist/chunks/chunk-2S45NNTL.js +2 -0
  8. package/dist/chunks/chunk-4JFGT4PN.js +2 -0
  9. package/dist/chunks/chunk-4JRJU5F5.js +2 -0
  10. package/dist/chunks/{chunk-KY53MB3J.js → chunk-5NW4WT4F.js} +2 -2
  11. package/dist/chunks/chunk-6ZGEYAFC.js +2 -0
  12. package/dist/chunks/{chunk-XR7Y4ZV6.js → chunk-7D7FBLWD.js} +2 -2
  13. package/dist/chunks/chunk-ANFN3X2M.js +2 -0
  14. package/dist/chunks/{chunk-NCRL33PQ.js → chunk-AS2XTRHH.js} +2 -2
  15. package/dist/chunks/chunk-BJ5WAL2C.js +2 -0
  16. package/dist/chunks/{chunk-EIUK6TKF.js → chunk-CEOSH3H2.js} +2 -2
  17. package/dist/chunks/{chunk-VZSQAGL2.js → chunk-CMNKXRZF.js} +2 -2
  18. package/dist/chunks/{chunk-XEJX5HBJ.js → chunk-CNJLPH6W.js} +2 -2
  19. package/dist/chunks/{chunk-TTOJDLIQ.js → chunk-DXSVV47D.js} +2 -2
  20. package/dist/chunks/{chunk-GIIURG5X.js → chunk-FAKOND5W.js} +2 -2
  21. package/dist/chunks/chunk-FCGTZ6BD.js +2 -0
  22. package/dist/chunks/{chunk-O4D43LWM.js → chunk-FELX2TZZ.js} +2 -2
  23. package/dist/chunks/{chunk-EB45CDFA.js → chunk-G4B2SQR6.js} +2 -2
  24. package/dist/chunks/chunk-HPIZAWMT.js +2 -0
  25. package/dist/chunks/chunk-I5XUWUEV.js +2 -0
  26. package/dist/chunks/{chunk-JG4TWDQ4.js → chunk-ILQ4VWSD.js} +2 -2
  27. package/dist/chunks/chunk-JLFRYDYO.js +2 -0
  28. package/dist/chunks/{chunk-GTSK4IN4.js → chunk-JXKHFSGK.js} +1 -1
  29. package/dist/chunks/{chunk-YMI33F7W.js → chunk-LBU73UMS.js} +2 -2
  30. package/dist/chunks/{chunk-ZRKXHVTJ.js → chunk-LSZTDKIB.js} +2 -2
  31. package/dist/chunks/chunk-LWFKGF43.js +2 -0
  32. package/dist/chunks/{chunk-NCDPZSI2.js → chunk-M5J3DHXB.js} +2 -2
  33. package/dist/chunks/{chunk-DD2GG4EC.js → chunk-MOYWWJP4.js} +1 -1
  34. package/dist/chunks/{chunk-I2KJMF4G.js → chunk-MPBFXHXT.js} +1 -1
  35. package/dist/chunks/chunk-NWNJEAKI.js +2 -0
  36. package/dist/chunks/{chunk-GOYTZ5RB.js → chunk-OTETSONJ.js} +2 -2
  37. package/dist/chunks/{chunk-V54MBEJM.js → chunk-QH4GK3JN.js} +2 -2
  38. package/dist/chunks/chunk-QVE7V5UG.js +2 -0
  39. package/dist/chunks/{chunk-RNGDVSTS.js → chunk-RMGEIU4Z.js} +2 -2
  40. package/dist/chunks/{chunk-LKKUUREA.js → chunk-SAFH76DR.js} +2 -2
  41. package/dist/chunks/{chunk-QCPGV7XH.js → chunk-SJJJ7Y4X.js} +2 -2
  42. package/dist/chunks/{chunk-L77QFL3C.js → chunk-TVU4N6BA.js} +2 -2
  43. package/dist/chunks/{chunk-6MLDKHTY.js → chunk-U6RXYALO.js} +2 -2
  44. package/dist/chunks/chunk-VNLSP22M.js +2 -0
  45. package/dist/chunks/chunk-W4EITKLJ.js +2 -0
  46. package/dist/chunks/{chunk-JHABMYNH.js → chunk-WWRKCRTZ.js} +1 -1
  47. package/dist/chunks/{chunk-NPWWGIFG.js → chunk-XHHDBEHB.js} +2 -2
  48. package/dist/chunks/{chunk-72I7GDWL.js → chunk-XJMBX6A2.js} +2 -2
  49. package/dist/chunks/chunk-YZ6SBFFG.js +2 -0
  50. package/dist/descriptive/qcc.d.ts +320 -0
  51. package/dist/descriptive/qcc.js +524 -0
  52. package/dist/descriptive/qccTools.d.ts +301 -0
  53. package/dist/descriptive/qccTools.js +390 -0
  54. package/dist/descriptive.js +2 -2
  55. package/dist/distributions/normal.d.ts +4 -0
  56. package/dist/distributions/normal.js +4 -2
  57. package/dist/distributions.js +2 -2
  58. package/dist/entries/descriptive.d.ts +2 -0
  59. package/dist/entries/descriptive.js +2 -0
  60. package/dist/entries/regression.d.ts +1 -0
  61. package/dist/entries/regression.js +2 -0
  62. package/dist/entries/tests.d.ts +1 -0
  63. package/dist/entries/tests.js +1 -0
  64. package/dist/htest/timeROC.d.ts +564 -0
  65. package/dist/htest/timeROC.js +1106 -0
  66. package/dist/linalg.js +2 -2
  67. package/dist/mixed.js +2 -2
  68. package/dist/models/betareg.js +14 -2
  69. package/dist/models/bradleyterry.d.ts +188 -0
  70. package/dist/models/bradleyterry.js +533 -0
  71. package/dist/models/survreg.d.ts +5 -0
  72. package/dist/models/survreg.js +23 -3
  73. package/dist/models/tobit.js +16 -5
  74. package/dist/multivariate.js +2 -2
  75. package/dist/numerics.js +2 -2
  76. package/dist/regression.js +3 -3
  77. package/dist/rstats.js +18 -18
  78. package/dist/special.js +2 -2
  79. package/dist/tests.js +15 -15
  80. package/dist/timeseries.js +2 -2
  81. package/package.json +1 -1
  82. package/dist/chunks/chunk-23QCIPET.js +0 -2
  83. package/dist/chunks/chunk-3UEYA6VG.js +0 -2
  84. package/dist/chunks/chunk-3Y4DNK4O.js +0 -2
  85. package/dist/chunks/chunk-4BGGWQWS.js +0 -2
  86. package/dist/chunks/chunk-5UFVACSV.js +0 -2
  87. package/dist/chunks/chunk-5W2OZAHQ.js +0 -2
  88. package/dist/chunks/chunk-BWDXJL7T.js +0 -2
  89. package/dist/chunks/chunk-GLABB425.js +0 -2
  90. package/dist/chunks/chunk-JV3POOET.js +0 -2
  91. package/dist/chunks/chunk-K3YSXDTU.js +0 -2
  92. package/dist/chunks/chunk-LY2UZGUL.js +0 -2
  93. package/dist/chunks/chunk-PSQ6MLJM.js +0 -2
  94. package/dist/chunks/chunk-RM5D7Q7W.js +0 -2
  95. package/dist/chunks/chunk-SA2E5GVO.js +0 -2
  96. package/dist/chunks/chunk-T5ZALLTJ.js +0 -2
  97. package/dist/chunks/chunk-XPYZOG5H.js +0 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,45 @@ 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
+
24
+ ## 1.18.0 - 2026-11-26
25
+
26
+ ### Added
27
+
28
+ - **Control charts** in `/descriptive` (after the qcc package, values only, no plots): `qcc` (xbar, R, S, xbar.one, p, np,
29
+ c, u and g charts; sigma by UWAVE-R, MVLUE-R, UWAVE-SD, MVLUE-SD, RMSDF, moving ranges or SD; nsigmas or probability
30
+ limits; newdata; violations of the limits and of runs), `shewhartRules`, `cusum`, `ewma`, `ewmaSmooth`, `ocCurves`,
31
+ `processCapability` (Cp, Cp_l, Cp_u, Cp_k, Cpm with confidence limits), `mqcc` (Hotelling's T2 for subgroups and for
32
+ individual observations, phase I and prediction limits), `qccOverdispersionTest`, `paretoChart` (the table) and
33
+ `qccGroups`; and `medianChart`, the median (Me-R) chart with the JIS factors (not in R).
34
+ - **Paired comparisons** in `/regression`: `btm` (after `BradleyTerry2::BTm`: abilities with a reference player,
35
+ contest-level variables such as home advantage, logit, probit and cauchit links, and player covariates with random
36
+ player effects fitted by PQL to the REML fixed point), `btAbilities`, `countsToBinomial`, and quasi variances
37
+ `qvcalc` and `worstErrors` (after the qvcalc package).
38
+
39
+ ### Fixed
40
+
41
+ - `tobit` and `survreg` with a covariate that has a large common value (x + 1e6 and beyond) gave NaN coefficients; they
42
+ now give R's fit. Their standard errors, and `tobitSummary`'s Wald test, stay exact for covariates near 1e±300.
43
+ - `betaregConfint` and `betaregSummary`: standard errors exact for covariates near 1e±300 (they were off or Infinity).
44
+ - `johnsonNeyman`: bounds exact for an outcome near 1e±150 (they were Infinity or 31% off).
45
+ - `sobelTest`: the standard error by `hypot`; `sobelTest`, `mediationMonteCarlo` and `moderatedMediation` stop with an
46
+ error, as `mediate` does, where the coefficient variances leave the double range (about 1e±150 and beyond), instead
47
+ of giving Infinity, 0 or a wrong interval.
48
+
10
49
  ## 1.17.0 - 2026-11-25
11
50
 
12
51
  ### 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.17.0。** R の stats パッケージの数値計算の中心
19
+ 状態: **1.19.0。** R の stats パッケージの数値計算の中心
20
20
  (分布・記述統計・検定・線形モデル・特殊関数・数値計算・線形代数の基本) を、R と同じ結果でカバーすることを目指しています。残っている作業は
21
21
  [ROADMAP.ja.md](ROADMAP.ja.md)、変更履歴は [CHANGELOG.md](CHANGELOG.md) (英語) にあります。
22
22
 
@@ -220,14 +220,14 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
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`, `mvrnorm` (`MASS::mvrnorm`) |
221
221
  | 時系列 | `acf`、`pacf`、`ccf` (`stats::acf`、`stats::pacf`、`stats::ccf`)、`@numero-uno-jpn/rstats/timeseries` |
222
222
  | 因果推論 | `match` (傾向スコアのマッチング: `ties = FALSE`・`replace = FALSE` の `Matching::Match`。ATT・ATE・ATC、1:M、キャリパー)、`matchWeights` (`cobalt::get.w`)、`weightit` (逆確率重み: glm・cbps・ipt・ebal の `WeightIt::weightit`。ATE・ATT・ATC・ATO)、`trimWeights`・`weightSummary`、`balTab` (マッチング・重み付けの前後の標準化平均差と分散比: `cobalt::bal.tab`)、`tableOneSmd` (`tableone::ExtractSmd`)、`mediate` (因果媒介分析: `mediation::mediate`、準ベイズ近似とブートストラップ)、`simSlopes`・`johnsonNeyman` (`interactions::sim_slopes`)、`sobelTest`・`mediationMonteCarlo`・`moderatedMediation` (index of moderated mediation)、`@numero-uno-jpn/rstats/causal` |
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
+ | 記述統計 | `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`。管理図 (qcc): `qcc` (xbar・R・S・個別値・p・np・c・u・g)、`shewhartRules`、`cusum`、`ewma`、`ewmaSmooth`、`ocCurves`、`processCapability`、`mqcc` (Hotelling の T2)、`qccOverdispersionTest`、`paretoChart`、`qccGroups`、メディアン管理図 `medianChart` |
224
224
  | 検定 | `tTest`, `chisqTest`, `fisherTest`, `wilcoxTest`, `corTest`, `binomTest`, `poissonTest`, `propTest`, `mcnemarTest`, `varTest`, `bartlettTest`, `kruskalTest`, `friedmanTest`, `quadeTest`, `flignerTest`, `moodTest`, `onewayTest`, `shapiroTest`, `mantelhaenTest`, `ansariTest`, `ksTest`, `pairwiseTTest`, `pairwiseWilcoxTest`, `pairwisePropTest`, `aov` (一元配置。表は当てはめの `aovSummary`), `TukeyHSD`, `zTest`, `brunnerMunzelTest`, `tamhaneT2Test` (Tamhane の T2 と T2')、`pageTest`、`grubbsTest`・`pgrubbs`・`qgrubbs`、`pAdjust` (`p.adjust`) |
225
225
  | 分散分析 | formula で呼ぶ `aov` と `aovSummary` (多元、交互作用、共変量、`Error()` の層), `anova` (`anova.lm`。逐次の表とモデルの比較), `Anova` (car の Type II と III), `aovEz` (afex。反復測定と混合計画、Greenhouse-Geisser と Huynh-Feldt の補正、一般化 η² と偏 η²), `mauchlyTest` (`mauchly.test`) |
226
226
  | 効果量と検出力 | `cohensD`, `hedgesG` (effectsize。信頼区間は厳密な限界), `etaSquared`, `omegaSquared`, `epsilonSquared` (偏・一般化。`anova` と `Anova` の表から), `powerTTest`, `powerPropTest`, `powerAnovaTest` (`power.*.test`), `pwrTTest`, `pwrT2nTest`, `pwr2pTest`, `pwr2p2nTest`, `pwrPTest`, `pwrNormTest`, `pwrRTest`, `pwrChisqTest`, `pwrAnovaTest`, `pwrF2Test`, `esH`, `esW1`, `esW2`, `cohenES` (pwr) |
227
227
  | 試験デザインの標本サイズと検出力 | `epiSsequb`・`epiSsequc`・`epiSsninfb`・`epiSsninfc`・`epiSssupb`・`epiSssupc` (epiR: 比率と平均の同等性・非劣性・優越性)、`powerPaired2x2` (対応のある 2 × 2 表の正確な McNemar 検定の検出力)、`ssizeCT`・`powerCT`・`ssizeEpi`・`powerEpi`・`numDEpi` (生存時間の標本サイズと検出力)、`ph2simon` (Simon の 2 段階デザイン) |
228
228
  | メタアナリシス | `escalc` (効果量と標本分散)、`rma` (等効果・ランダム効果のメタアナリシスとメタ回帰)、`confintRma`・`predictRma`・`regtest` (metafor) |
229
229
  | 線形モデル | `lm` (formula とデータフレーム、または行列で渡す。`summary` の値も返す), `modelMatrix` (`model.matrix`), `confint`, `predict`。`glm` (formula とデータフレーム、または行列で渡す。R の `stats` のすべての族とリンク) と `glmSummary` (`summary.glm`)、`svyglm` (逆確率重みに対する `survey::svyglm`: デザインに基づく標準誤差)、`glmResiduals` (4 種類)、`glmHatvalues`、`glmRstandard`、`glmCooksDistance`、`glmPredict` (標準誤差つき)、`glmConfint` (プロファイル尤度、厳密な限界)、`glmAnova` (`anova.glm`)。`vcovHC`、`vcovCL` (sandwich: HC0〜HC5、一元と多元のクラスター)、`coeftest`、`coefci` (lmtest)。`step`、`stepAIC` (lm と glm の AIC・BIC による段階的な変数選択)、`drop1`、`add1`、`extractAIC` |
230
- | 回帰 | `tobit`・`tobitSummary` (AER: `survreg` の上の Tobit 回帰、下限・上限、survreg のどの分布でも)、`betareg`・`betaregSummary`・`betaregConfint`・`betaregPredict`・`betaregResiduals` (betareg: 精度が定数か回帰のベータ回帰、平均のリンク 6 つ、最尤・バイアス補正・バイアス減少)、`loglin`・`loglm`・`loglmResiduals`・`loglmAnova` (反復比例当てはめによる対数線形モデル)、`multinom`・`multinomSummary`・`multinomConfint`・`multinomPredict`・`multinomAnova`・`multinomVcov` (nnet: 重みと decay つきの多項ロジスティック回帰)、`polr`・`polrSummary`・`polrVcov`・`polrPredict`・`polrConfint`・`polrAnova` (MASS: logistic・probit・cloglog・loglog・cauchit のリンクによる順序ロジスティック回帰)、`rlm`・`rlmSummary`・`rlmVcov`・`psiHuber`・`psiHampel`・`psiBisquare` (MASS: M 推定と MM 推定によるロバスト回帰)、`nls`・`nlsSummary`・`nlsVcov`・`nlsPredict`・`nlsConfint`・`nlsAnova` (非線形最小二乗法: 既定・`plinear`・`port` のアルゴリズムと 10 個の自己開始モデル)、`rq`・`rqSummary`・`rqPredict`・`rqPredictInterval`・`rqAnova` (分位点回帰)、`geeglm`・`geeSummary`・`geeVcov`・`geePredict`・`geeAnova`・`geeQIC` (一般化推定方程式)、`glmnet`・`glmnetCoef`・`glmnetPredict`・`cvGlmnet` (Gaussian・binomial・Poisson・multinomial の正則化回帰)。`@numero-uno-jpn/rstats/regression` から import します |
230
+ | 回帰 | `tobit`・`tobitSummary` (AER: `survreg` の上の Tobit 回帰、下限・上限、survreg のどの分布でも)、`betareg`・`betaregSummary`・`betaregConfint`・`betaregPredict`・`betaregResiduals` (betareg: 精度が定数か回帰のベータ回帰、平均のリンク 6 つ、最尤・バイアス補正・バイアス減少)、`loglin`・`loglm`・`loglmResiduals`・`loglmAnova` (反復比例当てはめによる対数線形モデル)、`multinom`・`multinomSummary`・`multinomConfint`・`multinomPredict`・`multinomAnova`・`multinomVcov` (nnet: 重みと decay つきの多項ロジスティック回帰)、`polr`・`polrSummary`・`polrVcov`・`polrPredict`・`polrConfint`・`polrAnova` (MASS: logistic・probit・cloglog・loglog・cauchit のリンクによる順序ロジスティック回帰)、`rlm`・`rlmSummary`・`rlmVcov`・`psiHuber`・`psiHampel`・`psiBisquare` (MASS: M 推定と MM 推定によるロバスト回帰)、`nls`・`nlsSummary`・`nlsVcov`・`nlsPredict`・`nlsConfint`・`nlsAnova` (非線形最小二乗法: 既定・`plinear`・`port` のアルゴリズムと 10 個の自己開始モデル)、`rq`・`rqSummary`・`rqPredict`・`rqPredictInterval`・`rqAnova` (分位点回帰)、`geeglm`・`geeSummary`・`geeVcov`・`geePredict`・`geeAnova`・`geeQIC` (一般化推定方程式)、`glmnet`・`glmnetCoef`・`glmnetPredict`・`cvGlmnet` (Gaussian・binomial・Poisson・multinomial の正則化回帰)、`btm`・`btAbilities`・`countsToBinomial` (BradleyTerry2: 一対比較、対象の共変量と変量効果の PQL も)、`qvcalc`・`worstErrors` (準分散)。`@numero-uno-jpn/rstats/regression` から import します |
231
231
  | 多変量解析 | `manova`・`manovaSummary` (逐次 MANOVA: Pillai・Wilks・Hotelling-Lawley・Roy)、`lda`・`ldaPredict` (線形判別分析)、`cancor` (正準相関)、`dist`・`asDist`・`hclust`・`cutree`・`kmeans` (クラスタ分析)、`cmdscale` (古典的多次元尺度法)、`ca`・`caSummary`・`caCoord` (対応分析)、`mjca` (多重対応分析)、`sammon`・`isoMDS` (非計量多次元尺度法)。`@numero-uno-jpn/rstats/multivariate` から import します |
232
232
  | 混合モデル | `lmer` (lme4: REML と最尤法、相関のある変量効果と相関のない変量効果、交差と入れ子の群。`fixef`、`vcov`、`VarCorr`、`ranef`、`logLik`、`AIC`、`BIC`、`REMLcrit`、`isSingular`)、`lmerSummary`・`lmerContest`・`lmerAnova` (lmerTest: Satterthwaite の t 検定と F 検定、Type I/II/III の分散分析表。当てはめどうしの尤度比検定)、`glmer` (lme4: glm のすべての族、ラプラス近似と適応的 Gauss-Hermite 求積)、`glmerSummary`・`glmerAnova`・`glmerPredict`・`lmerPredict`・`confintLmer`・`confintGlmer`・`simulateLmer`・`simulateGlmer`。
233
233
  `@numero-uno-jpn/rstats/mixed` から import する |
@@ -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` を除く) | 334.0 KB |
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 で 334 KB) を jsDelivr から読み込めます。jsDelivr は、npm のリリースを
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.17.0/dist/rstats.js";
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.0.** The goal is to cover the numerical core of R's
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
 
@@ -218,14 +218,14 @@ eigen([[2, 1], [1, 3]]).values; // ≈ [3.618033989, 1.381966011]
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`, `mvrnorm` (`MASS::mvrnorm`) |
219
219
  | Time series | `acf`, `pacf`, `ccf` (`stats::acf`, `stats::pacf`, `stats::ccf`) from `@numero-uno-jpn/rstats/timeseries` |
220
220
  | Causal inference | `match` (propensity score matching: `Matching::Match` with `ties = FALSE`, `replace = FALSE`; ATT, ATE and ATC, 1:M, caliper), `matchWeights` (`cobalt::get.w`), `weightit` (inverse probability weights: `WeightIt::weightit` with glm, cbps, ipt and ebal; ATE, ATT, ATC and ATO), `trimWeights` and `weightSummary`, `balTab` (standardized mean differences and variance ratios before and after: `cobalt::bal.tab`) and `tableOneSmd` (`tableone::ExtractSmd`); `mediate` (causal mediation analysis: `mediation::mediate`, quasi-Bayesian and bootstrap), `simSlopes` and `johnsonNeyman` (`interactions::sim_slopes`), `sobelTest`, `mediationMonteCarlo` and `moderatedMediation` (the index of moderated mediation), from `@numero-uno-jpn/rstats/causal` |
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
+ | 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`; control charts (qcc): `qcc` (xbar, R, S, individual values, p, np, c, u, g), `shewhartRules`, `cusum`, `ewma`, `ewmaSmooth`, `ocCurves`, `processCapability`, `mqcc` (Hotelling's T2), `qccOverdispersionTest`, `paretoChart`, `qccGroups`, and the median chart `medianChart` |
222
222
  | Hypothesis tests | `tTest`, `chisqTest`, `fisherTest`, `wilcoxTest`, `corTest`, `binomTest`, `poissonTest`, `propTest`, `mcnemarTest`, `varTest`, `bartlettTest`, `kruskalTest`, `friedmanTest`, `quadeTest`, `flignerTest`, `moodTest`, `onewayTest`, `shapiroTest`, `mantelhaenTest`, `ansariTest`, `ksTest`, `pairwiseTTest`, `pairwiseWilcoxTest`, `pairwisePropTest`, `aov` (one way, a fit whose table is `aovSummary`), `TukeyHSD`, `zTest`, `brunnerMunzelTest`, `tamhaneT2Test` (Tamhane's T2/T2'), `pageTest`, `grubbsTest`, `pgrubbs`, `qgrubbs`, `pAdjust` (`p.adjust`) |
223
223
  | Analysis of variance | `aov` and `aovSummary` with a formula (several factors, interactions, covariates, `Error()` strata), `anova` (`anova.lm`, sequential and model comparison), `Anova` (car: types II and III), `aovEz` (afex: repeated-measures and mixed designs, Greenhouse-Geisser and Huynh-Feldt corrections, generalized and partial eta squared), `mauchlyTest` (`mauchly.test`) |
224
224
  | Effect sizes and power | `cohensD`, `hedgesG` (effectsize, with exact confidence limits), `etaSquared`, `omegaSquared`, `epsilonSquared` (partial, generalized, from `anova` and `Anova` tables); `powerTTest`, `powerPropTest`, `powerAnovaTest` (`power.*.test`); `pwrTTest`, `pwrT2nTest`, `pwr2pTest`, `pwr2p2nTest`, `pwrPTest`, `pwrNormTest`, `pwrRTest`, `pwrChisqTest`, `pwrAnovaTest`, `pwrF2Test`, `esH`, `esW1`, `esW2`, `cohenES` (pwr) |
225
225
  | Sample size and power for trial designs | `epiSsequb`, `epiSsequc`, `epiSsninfb`, `epiSsninfc`, `epiSssupb`, `epiSssupc` (epiR: equivalence, non-inferiority and superiority for proportions and means), `powerPaired2x2` (exact paired McNemar power), `ssizeCT`, `powerCT`, `ssizeEpi`, `powerEpi`, `numDEpi` (survival sample size and power), `ph2simon` (Simon two-stage designs) |
226
226
  | Meta-analysis | `escalc` (effect sizes and sampling variances), `rma` (equal- and random-effects meta-analysis and meta-regression), `confintRma`, `predictRma`, `regtest` (metafor) |
227
227
  | Linear models | `lm` (a formula and a data frame, or a matrix, with the `summary` quantities), `modelMatrix` (`model.matrix`), `confint`, `predict`; `glm` (a formula and a data frame, or a matrix; every family and link of R's `stats`) with `glmSummary` (`summary.glm`), `svyglm` (`survey::svyglm` for inverse probability weights: design-based standard errors), `glmResiduals` (the four kinds), `glmHatvalues`, `glmRstandard`, `glmCooksDistance`, `glmPredict` (with standard errors), `glmConfint` (profile likelihood, exact limits), `glmAnova` (`anova.glm`); `vcovHC`, `vcovCL` (sandwich: HC0 to HC5, one-way and multi-way clustered), `coeftest`, `coefci` (lmtest); `step`, `stepAIC` (stepwise selection by AIC or BIC for lm and glm), `drop1`, `add1`, `extractAIC` |
228
- | Regression | `tobit`, `tobitSummary` (AER: tobit regression on `survreg`, left and right limits, any survreg distribution); `betareg`, `betaregSummary`, `betaregConfint`, `betaregPredict`, `betaregResiduals` (betareg: beta regression with a constant or modelled precision, six mean links, maximum likelihood, bias-corrected and bias-reduced); `loglin`, `loglm`, `loglmResiduals`, `loglmAnova` (log-linear models by iterative proportional fitting); `multinom`, `multinomSummary`, `multinomConfint`, `multinomPredict`, `multinomAnova`, `multinomVcov` (nnet: multinomial logistic regression with weights and decay), `polr`, `polrSummary`, `polrVcov`, `polrPredict`, `polrConfint`, `polrAnova` (MASS: ordinal logistic regression with logistic, probit, cloglog, loglog and cauchit links); `rlm`, `rlmSummary`, `rlmVcov`, `psiHuber`, `psiHampel`, `psiBisquare` (MASS: robust M and MM regression); `nls`, `nlsSummary`, `nlsVcov`, `nlsPredict`, `nlsConfint`, `nlsAnova` (nonlinear least squares: default, `plinear` and `port` algorithms, and 10 self-starting models); `rq`, `rqSummary`, `rqPredict`, `rqPredictInterval`, `rqAnova` (quantile regression); `geeglm`, `geeSummary`, `geeVcov`, `geePredict`, `geeAnova`, `geeQIC` (generalized estimating equations); `glmnet`, `glmnetCoef`, `glmnetPredict`, `cvGlmnet` (penalized Gaussian, binomial, Poisson and multinomial regression), from `@numero-uno-jpn/rstats/regression` |
228
+ | Regression | `tobit`, `tobitSummary` (AER: tobit regression on `survreg`, left and right limits, any survreg distribution); `betareg`, `betaregSummary`, `betaregConfint`, `betaregPredict`, `betaregResiduals` (betareg: beta regression with a constant or modelled precision, six mean links, maximum likelihood, bias-corrected and bias-reduced); `loglin`, `loglm`, `loglmResiduals`, `loglmAnova` (log-linear models by iterative proportional fitting); `multinom`, `multinomSummary`, `multinomConfint`, `multinomPredict`, `multinomAnova`, `multinomVcov` (nnet: multinomial logistic regression with weights and decay), `polr`, `polrSummary`, `polrVcov`, `polrPredict`, `polrConfint`, `polrAnova` (MASS: ordinal logistic regression with logistic, probit, cloglog, loglog and cauchit links); `rlm`, `rlmSummary`, `rlmVcov`, `psiHuber`, `psiHampel`, `psiBisquare` (MASS: robust M and MM regression); `nls`, `nlsSummary`, `nlsVcov`, `nlsPredict`, `nlsConfint`, `nlsAnova` (nonlinear least squares: default, `plinear` and `port` algorithms, and 10 self-starting models); `rq`, `rqSummary`, `rqPredict`, `rqPredictInterval`, `rqAnova` (quantile regression); `geeglm`, `geeSummary`, `geeVcov`, `geePredict`, `geeAnova`, `geeQIC` (generalized estimating equations); `glmnet`, `glmnetCoef`, `glmnetPredict`, `cvGlmnet` (penalized Gaussian, binomial, Poisson and multinomial regression); `btm`, `btAbilities`, `countsToBinomial` (BradleyTerry2: paired comparisons, with player covariates and random effects by PQL), `qvcalc`, `worstErrors` (quasi variances), from `@numero-uno-jpn/rstats/regression` |
229
229
  | Multivariate analysis | `manova`, `manovaSummary` (sequential MANOVA: Pillai, Wilks, Hotelling-Lawley and Roy); `lda`, `ldaPredict` (linear discriminant analysis); `cancor` (canonical correlation); `dist`, `asDist`, `hclust`, `cutree`, `kmeans` (cluster analysis); `cmdscale` (classical multidimensional scaling); `ca`, `caSummary`, `caCoord` (correspondence analysis); `mjca` (multiple correspondence analysis); `sammon` and `isoMDS` (non-metric multidimensional scaling), from `@numero-uno-jpn/rstats/multivariate` |
230
230
  | Mixed models | `lmer` (lme4: REML and ML, correlated and uncorrelated random effects, crossed and nested grouping factors; `fixef`, `vcov`, `VarCorr`, `ranef`, `logLik`, `AIC`, `BIC`, `REMLcrit`, `isSingular`), `lmerSummary`, `lmerContest` and `lmerAnova` (lmerTest: Satterthwaite's t- and F-tests, Type I/II/III ANOVA tables; likelihood-ratio comparison of fits), `glmer` (lme4: all glm families, Laplace approximation and adaptive Gauss-Hermite quadrature), `glmerSummary`, `glmerAnova`, `glmerPredict`, `lmerPredict`, `confintLmer`, `confintGlmer`, `simulateLmer` and
231
231
  `simulateGlmer`, from `@numero-uno-jpn/rstats/mixed` |
@@ -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`) | 334.0 KB |
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`, 334 KB gzipped) from jsDelivr, which serves each npm release:
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.17.0/dist/rstats.js";
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
  ```
@@ -25,6 +25,16 @@ const MODERATED_MEDIATION_KEYS = /* @__PURE__ */ new Set([
25
25
  "treat", "mediator",
26
26
  ]);
27
27
  /** A coefficient and its variance, by name */
28
+ /**
29
+ * Variances outside the normal doubles (variables on scales beyond about 1e+-150 give coefficient variances of 1e+-300
30
+ * and more, which overflow or underflow): an error, as mediate's, where the formulas would give Infinity, 0 or NaN
31
+ * silently. R's lm reports such variances as NA or 0 (experiments/qccbt118-old-extreme.R).
32
+ */
33
+ function checkRange(V, role) {
34
+ const MIN = 2 ** -1022, MAX = Number.MAX_VALUE;
35
+ if (V.some((r, i) => r.some((v) => !Number.isFinite(v)) || !(r[i] >= MIN && r[i] <= MAX)))
36
+ throw new RangeError(`the ${role} model's coefficient covariance is out of the double range (rescale the variables)`);
37
+ }
28
38
  function coefficient(fit, name, role) {
29
39
  const cov = modelCovariance(fit);
30
40
  const k = cov.names.indexOf(name);
@@ -62,8 +72,11 @@ function coefficient(fit, name, role) {
62
72
  export function sobelTest(modelM, modelY, options) {
63
73
  checkOptions(options, SOBEL_TEST_KEYS, "sobelTest"); // generated: option-keys.mjs
64
74
  const ca = coefficient(modelM, options.treat, "mediator"), cb = coefficient(modelY, options.mediator, "outcome");
75
+ checkRange([[ca.v]], "mediator");
76
+ checkRange([[cb.v]], "outcome");
65
77
  const a = ca.value, b = cb.value, sa = Math.sqrt(ca.v), sb = Math.sqrt(cb.v);
66
- const ab = a * b, se = Math.sqrt(b * b * sa * sa + a * a * sb * sb), z = ab / se;
78
+ // hypot: b^2 sa^2 + a^2 sb^2 overflows or underflows for variables far from 1 in size
79
+ const ab = a * b, se = Math.hypot(b * sa, a * sb), z = ab / se;
67
80
  return { a, sa, b, sb, ab, se, z, p: 2 * pnorm(Math.abs(z), { lowerTail: false }) };
68
81
  }
69
82
  const q7 = (v, level) => {
@@ -110,6 +123,8 @@ export function mediationMonteCarlo(modelM, modelY, options) {
110
123
  const ca = coefficient(modelM, options.treat, "mediator");
111
124
  const cb = coefficient(modelY, options.mediator, "outcome"), cc = coefficient(modelY, options.treat, "outcome");
112
125
  const iM = cb.names.indexOf(options.mediator), iX = cb.names.indexOf(options.treat);
126
+ checkRange([[ca.v]], "mediator");
127
+ checkRange([[cb.vcov[iM][iM], cb.vcov[iM][iX]], [cb.vcov[iX][iM], cb.vcov[iX][iX]]], "outcome");
113
128
  const aDraws = rnorm(nmc, { mean: ca.value, sd: Math.sqrt(ca.v) });
114
129
  const bc = mvrnorm(nmc, [cb.value, cc.value], [[cb.vcov[iM][iM], cb.vcov[iM][iX]], [cb.vcov[iX][iM], cb.vcov[iX][iX]]]);
115
130
  const ind = aDraws.map((a, j) => a * bc[j][0]), dir = bc.map((r) => r[1]), tot = ind.map((v, j) => v + dir[j]);
@@ -212,6 +227,8 @@ export function moderatedMediation(modelM, modelY, data, options) {
212
227
  const all = "family" in fit ? fit.model.columnNames : fit.coefNames;
213
228
  return fit.coefficients[all.indexOf(nm)];
214
229
  });
230
+ checkRange(covM.vcov, "mediator");
231
+ checkRange(covY.vcov, "outcome");
215
232
  const bm = mvrnorm(nmc, coefOf(modelM, covM.names), covM.vcov), bo = mvrnorm(nmc, coefOf(modelY, covY.names), covY.vcov);
216
233
  const cm = coefOf(modelM, covM.names), co = coefOf(modelY, covY.names);
217
234
  const find = (names, a, b) => {
@@ -52,7 +52,16 @@ function jn(q, alpha) {
52
52
  throw new RangeError("alpha must be in (0, 1)");
53
53
  const crit = qt(1 - alpha / 2, q.df);
54
54
  const c2 = crit * crit;
55
- const A = q.b3 * q.b3 - c2 * q.v33, B = 2 * (q.b1 * q.b3 - c2 * q.v13), C = q.b1 * q.b1 - c2 * q.v11;
55
+ // The quadratic on rescaled coefficients: the outcome's unit k (a power of 2 near sqrt(v11)) and the moderator's unit m
56
+ // (a power of 2 near sqrt(v11 / v33)), so that its coefficients are near 1; the bounds are scaled back by m exactly.
57
+ // Without this, an outcome near 1e+-150 or a moderator near 1e+-300 overflows or underflows in B^2 - 4 A C.
58
+ const MIN = 2 ** -1022, MAX = Number.MAX_VALUE;
59
+ if (![q.v11, q.v33].every((v) => v >= MIN && v <= MAX) || !Number.isFinite(q.v13)) {
60
+ throw new RangeError("the model's coefficient covariance is out of the double range (rescale the variables)");
61
+ }
62
+ const k = 2 ** Math.round(Math.log2(q.v11) / 2), m = 2 ** Math.round((Math.log2(q.v11) - Math.log2(q.v33)) / 2);
63
+ const b1 = q.b1 / k, b3 = q.b3 / k * m, v11 = q.v11 / k / k, v13 = q.v13 / k / k * m, v33 = q.v33 / k / k * m * m;
64
+ const A = b3 * b3 - c2 * v33, B = 2 * (b1 * b3 - c2 * v13), C = b1 * b1 - c2 * v11;
56
65
  const disc = B * B - 4 * A * C;
57
66
  const lo = Math.min(...q.w), hi = Math.max(...q.w);
58
67
  const modrange = [lo, hi];
@@ -66,7 +75,7 @@ function jn(q, alpha) {
66
75
  // the root without cancellation, then the other from the product of the roots
67
76
  const r1 = (-B - Math.sign(B || 1) * s) / (2 * A);
68
77
  const r2 = r1 === 0 ? (-B + Math.sign(B || 1) * s) / (2 * A) : C / (A * r1);
69
- bounds = r1 <= r2 ? [r1, r2] : [r2, r1];
78
+ bounds = r1 <= r2 ? [r1 * m, r2 * m] : [r2 * m, r1 * m];
70
79
  }
71
80
  // interactions reports inside = FALSE when the interval could not be found
72
81
  const inside = !failed && A < 0;
package/dist/causal.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.17.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 Ie,b as Ae}from"./chunks/chunk-JG4TWDQ4.js";import{p as Pe,x as ne,y as re}from"./chunks/chunk-EIUK6TKF.js";import{a as Ve}from"./chunks/chunk-GOYTZ5RB.js";import{a as ae}from"./chunks/chunk-TTOJDLIQ.js";import{h as Ce}from"./chunks/chunk-ZRKXHVTJ.js";import{a as pe}from"./chunks/chunk-GLABB425.js";import{b as Be}from"./chunks/chunk-JV3POOET.js";import"./chunks/chunk-3Y4DNK4O.js";import{f as Ge,h as be,j as Ue}from"./chunks/chunk-O4D43LWM.js";import"./chunks/chunk-LKKUUREA.js";import"./chunks/chunk-DD2GG4EC.js";import"./chunks/chunk-6MLDKHTY.js";import"./chunks/chunk-EB45CDFA.js";import{a as Ke}from"./chunks/chunk-XR7Y4ZV6.js";import{v as te}from"./chunks/chunk-4BGGWQWS.js";import"./chunks/chunk-SA2E5GVO.js";import"./chunks/chunk-XPYZOG5H.js";import"./chunks/chunk-K3YSXDTU.js";import{a as We}from"./chunks/chunk-KY53MB3J.js";import{e as qe,f as xe,k as ue}from"./chunks/chunk-BWDXJL7T.js";import"./chunks/chunk-23QCIPET.js";import{a as Ne}from"./chunks/chunk-RM5D7Q7W.js";import{e as He,f as De,g as ze,m as Fe,n as ge,o as we}from"./chunks/chunk-NCRL33PQ.js";import"./chunks/chunk-JHABMYNH.js";import"./chunks/chunk-I2KJMF4G.js";import"./chunks/chunk-72I7GDWL.js";import"./chunks/chunk-5UFVACSV.js";import"./chunks/chunk-LY2UZGUL.js";import{r as _e,s as Z,t as fe}from"./chunks/chunk-XEJX5HBJ.js";import{h as ee,k as B,l as Te}from"./chunks/chunk-YMI33F7W.js";import{l as K}from"./chunks/chunk-GTSK4IN4.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),l=Ye(r);return{values:r.map(o=>ee(o,-l)),unitExp:s+l}}var yt=["estimand","M","caliper"];function Et(e,s,n={}){K(n,yt,"match");let{estimand:t="ATT",M:r=1,caliper:l}=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(l!==void 0&&!(l>0&&Number.isFinite(l)))throw new RangeError("'caliper' must be a positive number");let m=[];for(let g=0;g<o;g++){let A=e[g];if(A===!0||A===1)m.push(!0);else if(A===!1||A===0)m.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(!m.includes(!0)||!m.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(l!==void 0){let{values:g,unitExp:A}=ie(a),x=0;for(let S of g)x+=S;x/=o;let k=0;for(let S of g)k+=(S-x)*(S-x);let $=ee(Math.sqrt(k/o),A);E=l*$,u=ee(E,c)}let v=[new Array(o).fill(!1),new Array(o).fill(!1)],f=[],d=[],w=[],M=[],y=0,h=0;for(let g=0;g<o;g++){let A=m[g];if(A?t==="ATC":t==="ATT")continue;let x=v[A?0:1],k=[];for(let O=0;O<o;O++){if(m[O]===A)continue;let F=Math.abs(a[g]-a[O]);F>E||x[O]||k.push({j:O,d:F})}if(k.length<r){h++,w.push(g+1);continue}let S=k.map(O=>O.d).sort((O,F)=>O-F)[r-1],_=k.filter(O=>O.d<=S).map(O=>O.j),z;if(_.length===r)z=_;else{M.push(_.length),z=[],_=_.slice();for(let O=0;O<r;O++){let F=_.length,D=Math.min(F-1,Math.floor(F*(1-ze())));z.push(_[D]),_.splice(D,1)}z.sort((O,F)=>O-F)}for(let O of z)x[O]=!0,f.push((A?g:O)+1),d.push((A?O:g)+1);y++}let p=new Set([...f,...d]),N=u===null?[]:w.filter(g=>!p.has(g)),b=[];return f.length===0&&b.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:N.length>0?N:null,caliper:l??null,ecaliper:u,nobs:o,wnobs:y,ndrops:h,estimand:t,M:r,tieSizes:M,warnings:b}}var Mt=["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 At(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 de(e,s,n,t){let r=0,l=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,l+=a*a,o+=a*e[c]}let m=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]-m)*(e[c]-m)}return[m,i/(r-l/r)]}function Nt(e,s,n={}){K(n,Mt,"balTab");let{match:t,weightit:r,binary:l="raw",levels:o={}}=n;if(t!==void 0&&r!==void 0)throw new RangeError("give 'match' or 'weightit', not both");let m=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(At);if(!E.includes(!0)||!E.includes(!1))throw new RangeError("'tr' must contain both groups");if(m!==void 0&&m.length!==u)throw new RangeError("'weights' must have the length of 'tr'");if(i==="ATO"&&m===void 0)throw new RangeError("estimand 'ATO' needs the weights");let v=[];r?.ps&&v.push(["prop.score",r.ps,"Distance"]);for(let[M,y]of Object.entries(s)){if(y.length!==u)throw new RangeError(`covariate '${M}' must have the length of 'tr'`);if(y.every(p=>typeof p=="number")){v.push([M,y,null]);continue}if(!y.every(p=>typeof p=="string"))throw new TypeError(`covariate '${M}' must be all numbers or all strings`);let h=o[M]??[...new Set(y)].sort(Ne);if(y.some(p=>!h.includes(p)))throw new RangeError(`covariate '${M}' has values not among its levels`);for(let p of h.length===2?h.slice(1):h)v.push([`${M}_${p}`,y.map(N=>N===p?1:0),null])}let f=E.map(()=>!0),d=r!==void 0,w={rows:v.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,y,h]of v){if(y.some(D=>!Number.isFinite(D)))throw new RangeError(`covariate '${M}' has missing or infinite values`);let p=h===null&&new Set(y).size<=2&&y.every(D=>D===0||D===1),N=p?null:ie(y),b=N===null?y:N.values,[g,A]=de(b,null,E,!0),[x,k]=de(b,null,E,!1),$;if(i==="ATO"){let[D,Q]=de(b,m,f,!0);$=Math.sqrt(p?D*(1-D):Q)}else{let D=p?[g*(1-g),x*(1-x)]:[A,k];if($=Math.sqrt(i==="ATT"?D[0]:i==="ATC"?D[1]:(D[0]+D[1])/2),ee($,N?.unitExp??0)<Math.sqrt(Number.EPSILON)){let[Q,V]=de(b,null,f,!0);$=Math.sqrt(p?Q*(1-Q):V)}}let S=p&&l==="raw"?1:$;if(w.type.push(h??(p?"Binary":"Contin.")),w.diffUn.push(g===x?0:(g-x)/S),w.vRatioUn.push(p||k===0?NaN:A/k),m===void 0){w.diffAdj.push(NaN),w.vRatioAdj.push(NaN);continue}let[_,z]=de(b,m,E,!0),[O,F]=de(b,m,E,!1);w.diffAdj.push(_===O?0:(_-O)/S),w.vRatioAdj.push(p||F===0?NaN:z/F)}for(let M of[!1,!0]){let y=0,h=0,p=0,N=0,b=0;for(let x=0;x<u;x++){if(E[x]!==M||(y++,c.has(x+1)&&b++,m===void 0))continue;let k=m[x];h+=k,p+=k*k,k>0&&N++}let g=M?w.observations.treated:w.observations.control;if(d){g.push(y,h*h/p);continue}let A=m===void 0?[NaN,NaN,NaN]:[h*h/p,N,y-N-b];a&&A.push(b),g.push(y,y,...A)}return w}function Rt(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 l=f=>f!==null&&!(typeof f=="number"&&Number.isNaN(f)),o=r.map(f=>e.filter((d,w)=>s[w]===f&&l(d)));if(!t){if(o.flat().some(h=>typeof h!="number"))throw new TypeError("'x' must be numeric unless factor: true");let f=ie(o.flat()).values,w=[f.slice(0,o[0].length),f.slice(o[0].length)].map(h=>{let p=h.reduce((N,b)=>N+b,0)/h.length;return[p,h.reduce((N,b)=>N+(b-p)*(b-p),0)/(h.length-1)]}),M=w[1][0]-w[0][0],y=Math.sqrt((w[0][1]+w[1][1])/2);return M===0?0:Math.abs(M)/y}let m=[...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=>m.slice(1).map(d=>f.filter(w=>w===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},(w,M)=>{let y=h=>d===M?h[d]*(1-h[d]):-h[d]*h[M];return(y(i[0])+y(i[1]))/2}));if(u.every(f=>f.every(d=>d===0)))return NaN;let E=Be(u),v=0;for(let f=0;f<a;f++)for(let d=0;d<a;d++)v+=c[f]*E[f][d]*c[d];return Math.sqrt(v)}var St=["method","link","estimand","stabilize"],Ot=["at","lower","treat"],oe=Number.EPSILON;function xt(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 Ct(e,s){let n=[],t=[],r={};for(let[l,o]of Object.entries(e)){if(o.length!==s)throw new RangeError(`covariate '${l}' 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 '${l}' has missing or infinite values`);n.push(l),t.push(c.slice());continue}if(!o.every(c=>typeof c=="string"))throw new TypeError(`covariate '${l}' must be all numbers or all strings`);let m=o,i=[...new Set(m)].sort(Ne);r[l]=i;for(let c of i.slice(1))n.push(l+c),t.push(m.map(a=>a===c?1:0))}return{names:n,columns:t,factors:r}}function Xe(e){return e.map(s=>{let n=s.reduce((r,l)=>r+l,0)/s.length,t=s.reduce((r,l)=>Math.max(r,Math.abs(l-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 l=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,v)=>u+E*c[v],0);for(let u=0;u<s;u++)o[u]-=a*c[u]}let m=Math.sqrt(o.reduce((i,c)=>i+c*c,0));m>1e-7*l&&(n.push(o.map(i=>i/m)),t.push(r))}return t}function rt(e,s){let n=s.length,t=e.map((o,m)=>[...o,s[m]]),r=0;for(let o of e)for(let m of o)r=Math.max(r,Math.abs(m));for(let o=0;o<n;o++){let m=o;for(let i=o+1;i<n;i++)Math.abs(t[i][o])>Math.abs(t[m][o])&&(m=i);if(!(Math.abs(t[m][o])>1e-13*r))return null;[t[o],t[m]]=[t[m],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 l=new Array(n).fill(0);for(let o=n-1;o>=0;o--){let m=t[o][n];for(let i=o+1;i<n;i++)m-=t[o][i]*l[i];l[o]=m/t[o][o]}return l}function $e(e,s){return Array.from({length:s},(n,t)=>[1,...e.map(r=>r[t])])}function Qe(e,s,n){let t=n.length,r=new Array(t).fill(0);r[0]=Math.log(n[0]/s.length);let l=c=>{let a=0;for(let u of s)a+=Math.exp(e[u].reduce((E,v,f)=>E+v*c[f],0));return a-n.reduce((u,E,v)=>u+E*c[v],0)},o=l(r),m=!1,i=1e-13*Math.max(1,Math.abs(n[0]));for(let c=0;c<200;c++){let a=n.map(h=>-h),u=Array.from({length:t},()=>new Array(t).fill(0));for(let h of s){let p=e[h],N=Math.exp(p.reduce((b,g,A)=>b+g*r[A],0));for(let b=0;b<t;b++){a[b]+=N*p[b];for(let g=0;g<=b;g++)u[b][g]+=N*p[b]*p[g]}}for(let h=0;h<t;h++)for(let p=h+1;p<t;p++)u[h][p]=u[p][h];let E=Math.max(...a.map(Math.abs));if(E<=i){m=!0;break}let v=rt(u,a.map(h=>-h));if(v===null||v.some(h=>!Number.isFinite(h)))break;let f=1e-12*(Math.abs(o)+1),d=1,w=r.map((h,p)=>h+v[p]),M=l(w);for(;!(M<=o+f)&&d>1e-10;)d/=2,w=r.map((h,p)=>h+d*v[p]),M=l(w);if(!(M<=o+f))break;let y=v.some((h,p)=>Math.abs(d*h)>1e-15*Math.max(1,Math.abs(r[p])));if(r.splice(0,t,...w),o=M,!y){m=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:m}}var kt={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=>_e(e)}};function jt(e,s,n,t,r){let l=s.length,o=r.length,m=r.slice(),i=d=>{let w=new Array(o).fill(0),M=Array.from({length:o},()=>new Array(o).fill(0));for(let y=0;y<l;y++){let h=e[y],p=h.reduce(($,S,_)=>$+S*d[_],0),N=t.p(p),b=t.q(p),g=t.d(p),A=s[y],x,k;n==="ATE"?(x=A?1/N:-1/b,k=A?-g/(N*N):-g/(b*b)):n==="ATT"?(x=A?1:-N/b,k=A?0:-g/(b*b)):n==="ATC"?(x=A?b/N:-1,k=A?-g/(N*N):0):(x=A?b:-N,k=-g);for(let $=0;$<o;$++){w[$]+=x*h[$];for(let S=0;S<o;S++)M[$][S]+=k*h[$]*h[S]}}return{g:w,J:M}},c=d=>d.reduce((w,M)=>w+M*M,0),{g:a,J:u}=i(m),E=c(a),v=!1,f=1e-12*l;for(let d=0;d<200;d++){if(Math.max(...a.map(Math.abs))<=f){v=!0;break}let w=rt(u,a.map(N=>-N));if(w===null||w.some(N=>!Number.isFinite(N)))break;let M=1,y=m.map((N,b)=>N+w[b]),h=i(y),p=c(h.g);for(;!(p<E)&&M>1e-10;)M/=2,y=m.map((N,b)=>N+M*w[b]),h=i(y),p=c(h.g);if(!(p<E)){v=Math.max(...a.map(Math.abs))<=1e-8*l;break}m=y,a=h.g,u=h.J,E=p}return{eta:e.map(d=>d.reduce((w,M,y)=>w+M*m[y],0)),converged:v}}function Ze(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 Lt={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."},et={cbps:"covariate balancing propensity score weighting",ipt:"inverse probability tilting",ebal:"entropy balancing"};function _t(e,s,n={}){K(n,St,"weightit");let{method:t="glm",estimand:r="ATE",stabilize:l=!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 m=o==="ebal"?null:n.link??"logit";if(m!==null&&!{glm:["logit","probit","cauchit","cloglog"],cbps:["logit","probit"],ipt:["logit"]}[o].includes(m))throw new RangeError(`link '${m}' is not available for method '${o}'`);if((o==="ipt"||o==="ebal")&&r==="ATO")throw new RangeError(`"ATO" is not an allowable estimand for ${et[o]} with a binary treatment. Only "ATE", "ATT", and "ATC" are allowed.`);let c=[];if(l&&o==="glm"&&r!=="ATE")throw new RangeError('`stabilize` can only be supplied when `estimand = "ATE"`.');l&&o!=="glm"&&c.push(`\`stabilize\` cannot be used with ${et[o]} and will be ignored.`);let a=xt(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:v}=Ct(s,u);if(v.length===0)throw new RangeError("'covariates' must have at least one column");let f=$t(v.map(b=>ie(b).values)),d=a.flatMap((b,g)=>b?[g]:[]),w=a.flatMap((b,g)=>b?[]:[g]),M=a.map((b,g)=>g),y=r==="ATT"?1:r==="ATC"?0:null,h=null,p,N=!0;if(o==="glm"){let b=we(()=>be($e(f,u).map(g=>g.slice(1)),a,{family:"binomial",link:m}));N=b.converged,h=b.fittedValues.map((g,A)=>m==="logit"&&Math.abs(b.linearPredictors[A])>30?b.linearPredictors[A]>0?1-oe:oe:Math.min(Math.max(g,oe),1-oe)),p=a.map((g,A)=>Ze(r,g,h[A],1-h[A])),h.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 b=Xe(f),g=$e(b,u),A=we(()=>be(g.map(S=>S.slice(1)),a,{family:"binomial",link:m})).coefficients.map(S=>Number.isFinite(S)?S:0),x=kt[m],k=jt(g,a,r,x,A);N=k.converged;let $=S=>Math.min(Math.max(S,oe),1-oe);h=k.eta.map(S=>$(x.p(S))),p=a.map((S,_)=>Ze(r,S,h[_],$(x.q(k.eta[_]))))}else{let b=Xe(f),g=$e(b,u),A=_=>g[0].map((z,O)=>_.reduce((F,D)=>F+g[D][O],0)),x={C:r!=="ATC",T:r!=="ATT"},k=o==="ebal"&&r==="ATE"?{C:A(M),T:A(M)}:{C:A(d),T:A(w)},$=x.C?Qe(g,w,k.C):null,S=x.T?Qe(g,d,k.T):null;if(N=($?.converged??!0)&&(S?.converged??!0),o==="ebal")p=a.map((_,z)=>_?S?Math.exp(S.eta[z]):1:$?Math.exp($.eta[z]):1);else{let _=r==="ATE"?1:0;p=a.map((z,O)=>z?S?_+Math.exp(S.eta[O]):1:$?_+Math.exp($.eta[O]):1),h=a.map((z,O)=>r==="ATT"?te($.eta[O]):r==="ATC"?te(-S.eta[O]):z?te(-S.eta[O]):te($.eta[O]))}}if(N||c.push(Lt[o]),l&&o==="glm"){let b=[w.length/u,d.length/u];p=p.map((g,A)=>g*b[a[A]])}return p.every(b=>Math.abs(b-1)<Math.sqrt(oe))&&c.push("All weights are 1, possibly indicating an estimation failure."),ge("weightit",{weights:p,ps:h,treat:a,estimand:r,method:o,link:m,stabilized:l&&o==="glm",focal:y,columnNames:E,converged:N,warnings:c})}function tt(e,s,n,t){let r=e.slice();if(s.length===0)return r;let l=s.map(i=>e[i]),o,m;if(n<1){let i=n<.5?1-n:n;o=ae(l,i,{type:3}),m=ae(l,1-i,{type:3})}else{if(!Number.isInteger(n))throw new RangeError("'at' must be below 1 or a whole number");if(n>=l.length)return null;let i=n>l.length/2?l.length-n:n,c=l.slice().sort((a,u)=>a-u);o=c[c.length-1-i],m=c[i]}for(let i of s)e[i]>o&&(r[i]=o),t&&e[i]<m&&(r[i]=m);return r}var nt=e=>`\`at\` must be less than ${e}, the number of units. Weights will not be trimmed.`;function qt(e,s){K(s,Ot,"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 m=Array.from(e);if(s.treat!==void 0&&s.treat.length!==m.length)throw new RangeError("'treat' must have the length of 'w'");let i=tt(m,m.map((c,a)=>a),n,t);return i===null?(Fe("trimWeights",[nt(m.length)]),m):i}let r=e,l=r.treat.flatMap((m,i)=>r.focal===null||m!==r.focal?[i]:[]),o=tt(r.weights,l,n,t);return o===null?ge("trimWeights",{...r,weights:r.weights.slice(),warnings:[nt(l.length)]}):{...r,weights:o,warnings:r.warnings.slice()}}function ot(e,s){let n=s.map(a=>e[a]),t=n.length,r=0,l=0;for(let a of n)r+=a,l+=a*a;let o=r/t,m=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(m/(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/l}}function Ht(e){let s=e.treat.flatMap((t,r)=>t?[r]:[]),n=e.treat.flatMap((t,r)=>t?[]:[r]);return{treated:ot(e.weights,s),control:ot(e.weights,n),stabilized:e.stabilized}}var Dt=new Set(["treat","mediator","treatValue","controlValue","covariates","sims","boot","bootCiType","confLevel","robustSE"]);function st(e,s,n){let t=Ge(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,l=a=>a;if(r){let a=e;if(a.family==="binomial"&&(a.link==="logit"||a.link==="probit"))l=Ue(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,m=Ke(We(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(m.frame.rows.length!==i.length||m.frame.rows.some((a,u)=>a!==i[u])||m.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:l,d:m,rows:i}}function ve(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 ft(e,s,n){let t=e.d.frame.variables.map((r,l)=>{let o=s.get(l);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 at(e,s,n,t){let r=e.length,l=2**-1022,o=Number.MAX_VALUE;if(s.some((a,u)=>a.some(E=>!Number.isFinite(E))||!(a[u]>=l&&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 m=Ie(s),i=ue(n*r),c=[];for(let a=0;a<n;a++){let u=[];for(let E=0;E<r;E++){let v=0;for(let f=0;f<r;f++)v+=i[a*r+f]*m[f][E];u.push(e[E]+v)}c.push(u)}return c}function Se(e,s){let n=new Map(e.mCov);return n.set(e.mTreat,s),ft(e.m,n,e.n)}function Ee(e,s,n){let t=new Map(e.yCov);return t.set(e.yTreat,s),t.set(e.yMed,n),ft(e.y,t,e.n)}function Re(e,s,n,t){return Ee(e,s,n).map(r=>e.y.linkinv(ce(r,t)))}var ye=(e,s)=>B(e.map((n,t)=>n-s[t]));function ut(e,s,n,t){if(Oe(e.y)){let i=Ee(e,e.t0,s),c=Ee(e,e.t0,n),a=Ee(e,e.t1,s),u=Ee(e,e.t1,n),E=(v,f)=>B(v.map((d,w)=>{let M=0;for(let y=0;y<d.length;y++)M+=(d[y]-f[w][y])*t[y];return M}));return[E(i,c),E(a,u),E(u,c),E(a,i),E(a,c)]}let r=Re(e,e.t0,s,t),l=Re(e,e.t0,n,t),o=Re(e,e.t1,s,t),m=Re(e,e.t1,n,t);return[ye(r,l),ye(o,m),ye(m,l),ye(o,r),ye(o,l)]}function ke(e,s,n,t){let r=e.n,l=Se(e,e.t1).map(c=>ce(c,s)),o=Se(e,e.t0).map(c=>ce(c,s)),m,i;if(Oe(e.m)){let c=ue(r,{sd:n});m=l.map((a,u)=>a+c[u]),i=o.map((a,u)=>a+c[u])}else m=l.map(c=>pe(1,e.m.linkinv(c))),i=o.map(c=>pe(1,e.m.linkinv(c)));return ut(e,m,i,t)}var Oe=e=>!e.isGlm||e.fit.family==="gaussian",je=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 it=(e,s,n)=>{let t=ae(e,[s,n],{type:7});return[t[0],t[1]]};function Le(e,s,n,t){K(t,Dt,"mediate");let{treat:r,mediator:l}=t;if(typeof r!="string"||typeof l!="string")throw new TypeError("'treat' and 'mediator' are required");let o=t.treatValue??1,m=t.controlValue??0;if(!Number.isFinite(o)||!Number.isFinite(m))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 v=[];c&&E&&v.push("'robustSE' is ignored for nonparametric bootstrap");let f=st(e,n,"mediator"),d=st(s,n,"outcome");if(!Oe(f)&&e.family!=="binomial")throw new RangeError("unsupported mediator model");if(f.d.terms.variables[0]!==l)throw new RangeError(`the mediator model's response must be '${l}'`);if(f.rows.length!==d.rows.length||f.rows.some((T,C)=>T!==d.rows[C]))throw new RangeError("number of observations do not match between mediator and outcome models");let w=f.rows.length,M=Object.entries(t.covariates??{});for(let[,T]of M)if(!Number.isFinite(T))throw new RangeError("covariate values must be finite");let y={m:f,y:d,treat:r,mediator:l,t1:o,t0:m,n:w,mTreat:ve(f,r,"mediator",!0),yTreat:ve(d,r,"outcome",!0),yMed:ve(d,l,"outcome",!0),mCov:M.map(([T,C])=>[ve(f,T,"mediator",!1),C]).filter(([T])=>T>=0),yCov:M.map(([T,C])=>[ve(d,T,"outcome",!1),C]).filter(([T])=>T>=0)};if(M.some(([T])=>!f.d.terms.variables.includes(T)&&!d.d.terms.variables.includes(T)))throw new RangeError("covariates must be variables of the models");let h=Oe(f),p,N;if(c){let T=Ve(w,{size:w*i,replace:!0}),C=[...new Set([...f.d.terms.variables,...d.d.terms.variables])],I=h?je(f):NaN;ke(y,f.coef,I,d.coef),p=[];for(let U=0;U<i;U++){let G=Array.from({length:w},(H,j)=>f.rows[T[U+j*i]]),Y=Object.fromEntries(C.map(H=>{let j=n[H];return[H,G.map(R=>j[R])]})),J=ct(f,Y),X=ct(d,Y);p.push(ke(y,mt(J,f,v),h?je({...f,fit:J,isGlm:"family"in J}):NaN,mt(X,d,v)))}N=ke(y,f.coef,I,d.coef)}else{let T=E?re(e,{type:"HC3"}).vcov:ne(e).vcov,C=E?re(s,{type:"HC3"}).vcov:ne(s).vcov,I=at(f.coef,T,i,"mediator"),U=at(d.coef,C,i,"outcome"),G=Se(y,o),Y=Se(y,m),J=Array.from({length:i},()=>new Array(w)),X=Array.from({length:i},()=>new Array(w));if(h){let H=ue(i*w,{sd:je(f)});for(let j=0;j<w;j++)for(let R=0;R<i;R++)J[R][j]=ce(G[j],I[R])+H[j*i+R],X[R][j]=ce(Y[j],I[R])+H[j*i+R]}else{for(let H=0;H<w;H++)for(let j=0;j<i;j++)J[j][H]=pe(1,f.linkinv(ce(G[H],I[j])));for(let H=0;H<w;H++)for(let j=0;j<i;j++)X[j][H]=pe(1,f.linkinv(ce(Y[H],I[j])))}p=I.map((H,j)=>ut(y,J[j],X[j],U[j]))}let b=T=>p.map(C=>C[T]),g=b(0),A=b(1),x=b(2),k=b(3),$=b(4),S=g.map((T,C)=>T/$[C]),_=A.map((T,C)=>T/$[C]),z=g.map((T,C)=>(T+A[C])/2),O=x.map((T,C)=>(T+k[C])/2),F=S.map((T,C)=>(T+_[C])/2),D=(1-u)/2,Q=(1+u)/2,V=(T,C)=>{let I;if(c&&a==="bca"){let Y=B(T),J=0,X=0,H=0;for(let q of T){let W=Y-q;J+=W*W,X+=W*W*W,q<Y&&H++}let j=X/(6*J**1.5),R=fe(H/T.length),L=q=>Z(R+(R+q)/(1-j*(R+q)));I=it(T,L(fe(D)),L(fe(Q)))}else I=it(T,D,Q);let U=0,G=0;for(let Y of T)Y>0?U++:Y<0&&G++;return{estimate:C,ci:I,p:2*Math.min(U/T.length,G/T.length),sims:T}},P;if(N===void 0){let T=Ce(S),C=Ce(_);P=[B(g),B(A),B(x),B(k),B($),T,C,B(z),B(O),(T+C)/2]}else{let[T,C,I,U,G]=N;P=[T,C,I,U,G,T/G,C/G,(T+C)/2,(I+U)/2,(T/G+C/G)/2]}let le=d.d.terms.termLabels.some(T=>{let C=T.split(":");return C.length>1&&C.includes(r)&&C.includes(l)});return ge("mediate",{d0:V(g,P[0]),d1:V(A,P[1]),z0:V(x,P[2]),z1:V(k,P[3]),tau:V($,P[4]),n0:V(S,P[5]),n1:V(_,P[6]),dAvg:V(z,P[7]),zAvg:V(O,P[8]),nAvg:V(F,P[9]),treatValue:o,controlValue:m,nobs:w,sims:i,boot:c,bootCiType:a,confLevel:u,robustSE:E&&!c,INT:le,warnings:v})}function ct(e,s){let n={...e.options};return we(()=>e.isGlm?be(e.formula,s,n):Pe(e.formula,s,n))}var lt='prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases';function mt(e,s,n){let t="family"in e?e.model.columnNames:e.coefNames;return s.names.map(r=>{let l=t.indexOf(r);return l<0||Number.isNaN(e.coefficients[l])?(n.includes(lt)||n.push(lt),0):e.coefficients[l]})}var Vt=["pred","modx","modxValues","johnsonNeyman","jnAlpha","ciWidth","robust"],It=["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 l="family"in e,o=l?e.model.columnNames:e.coefNames;if(o===void 0)throw new TypeError("the model must be a formula fit of lm or glm");if(l&&e.family!=="binomial"&&e.family!=="gaussian")throw new RangeError("the model's family is not supported (binomial or gaussian)");let m=[`${n}:${t}`,`${t}:${n}`].find(d=>o.includes(d));if(!o.includes(n)||m===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(m);if(c<0||a<0)throw new RangeError("the predictor's or the interaction's coefficient is aliased");let u=e.coefficients,E=l?e.model.rows:e.rows,v=s[t];if(v===void 0)throw new RangeError(`object '${t}' not found`);let f=E.map(d=>Number(v[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(m)],v11:i.vcov[c][c],v13:i.vcov[c][a],v33:i.vcov[a][a],df:e.dfResidual,isGlm:l&&e.family==="binomial",w:f}}function ht(e,s){if(!(s>0&&s<1))throw new RangeError("alpha must be in (0, 1)");let n=xe(1-s/2,e.df),t=n*n,r=e.b3*e.b3-t*e.v33,l=2*(e.b1*e.b3-t*e.v13),o=e.b1*e.b1-t*e.v11,m=l*l-4*r*o,i=Math.min(...e.w),c=Math.max(...e.w),a=[i,c],u,E=!1;if(!(m>=0))u=[-1/0,1/0],E=!0;else{let d=Math.sqrt(m),w=(-l-Math.sign(l||1)*d)/(2*r),M=w===0?(-l+Math.sign(l||1)*d)/(2*r):o/(r*w);u=w<=M?[w,M]:[M,w]}let v=!E&&r<0,f=!(u[0]>i&&u[0]<c)&&!(u[1]>i&&u[1]<c);return{bounds:u,inside:v,failed:E,allSig:f,modrange:a,alpha:s}}function Ft(e,s,n){return K(n,It,"johnsonNeyman"),ht(dt(e,s,n.pred,n.modx,n.robust??!1),n.alpha??.05)}function Wt(e,s,n){K(n,Vt,"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 l=n.modxValues??"mean-plus-minus",o;if(l==="mean-plus-minus"){let v=B(t.w),f=Math.sqrt(Te(t.w));o=[v-f,v,v+f]}else if(Array.isArray(l)&&l.every(v=>Number.isFinite(v)))o=[...l];else throw new RangeError('modxValues must be "mean-plus-minus" or finite numbers');let m=t.isGlm?fe((1+r)/2):xe((1+r)/2,t.df),i=o.map(v=>t.b1+t.b3*v),c=o.map(v=>Math.sqrt(t.v11+2*v*t.v13+v*v*t.v33)),a=i.map((v,f)=>v/c[f]),u=a.map(v=>2*(t.isGlm?Z(-Math.abs(v)):qe(-Math.abs(v),t.df))),E={values:o,estimate:i,se:c,lower:i.map((v,f)=>v-m*c[f]),upper:i.map((v,f)=>v+m*c[f]),statistic:a,statisticName:t.isGlm?"z":"t",p:u};return(n.johnsonNeyman??!0)&&(E.jn=ht(t,n.jnAlpha??.05)),E}var Kt=["treat","mediator"],Gt=["nmc","confLevel","treat","mediator"],Pt=new Set(["moderator","treatValue","controlValue","wLow","wHigh","method","nmc","sims","confLevel","robustSE","treat","mediator"]);function Me(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 l="family"in e?e.model.columnNames:e.coefNames;return{value:e.coefficients[l.indexOf(s)],v:t.vcov[r][r],names:t.names,vcov:t.vcov}}function Ut(e,s,n){K(n,Kt,"sobelTest");let t=Me(e,n.treat,"mediator"),r=Me(s,n.mediator,"outcome"),l=t.value,o=r.value,m=Math.sqrt(t.v),i=Math.sqrt(r.v),c=l*o,a=Math.sqrt(o*o*m*m+l*l*i*i),u=c/a;return{a:l,sa:m,b:o,sb:i,ab:c,se:a,z:u,p:2*Z(Math.abs(u),{lowerTail:!1})}}var wt=(e,s)=>{let n=1-s,t=ae(e,[n/2,1-n/2],{type:7});return[t[0],t[1]]};function bt(e){if(!(e>0&&e<1))throw new RangeError("confLevel must be in (0, 1)")}function Bt(e,s,n){K(n,Gt,"mediationMonteCarlo");let t=Math.trunc(n.nmc??2e4),r=n.confLevel??.95;if(bt(r),!(t>=2))throw new RangeError("nmc must be at least 2");let l=Me(e,n.treat,"mediator"),o=Me(s,n.mediator,"outcome"),m=Me(s,n.treat,"outcome"),i=o.names.indexOf(n.mediator),c=o.names.indexOf(n.treat),a=ue(t,{mean:l.value,sd:Math.sqrt(l.v)}),u=Ae(t,[o.value,m.value],[[o.vcov[i][i],o.vcov[i][c]],[o.vcov[c][i],o.vcov[c][c]]]),E=a.map((h,p)=>h*u[p][0]),v=u.map(h=>h[1]),f=E.map((h,p)=>h+v[p]),d=E.map((h,p)=>h/f[p]),w=l.value*o.value,M=m.value,y=(h,p)=>({estimate:h,ci:wt(p,r),sims:p});return{indirect:y(w,E),direct:y(M,v),total:y(w+M,f),proportion:y(w/(w+M),d)}}function pt(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 l=[...new Set(r)].sort((i,c)=>i-c);if(l.length===2)return[l[0],l[1]];let o=B(r),m=Math.sqrt(Te(r));return[o-m,o+m]}var gt=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:l,moderator:o}=t;if(typeof r!="string"||typeof l!="string"||typeof o!="string")throw new TypeError("'treat', 'mediator' and 'moderator' are required");let m=t.confLevel??.95;bt(m);let i=Yt(e),[c,a]=pt(n,i,r),[u,E]=pt(n,i,o),v=t.treatValue??a,f=t.controlValue??c,d=t.wLow??u,w=t.wHigh??E,M=t.method??(gt(e)&&gt(s)?"monteCarlo":"mediate"),y=(R,L)=>({estimate:R,ci:wt(L,m),sims:L}),h={method:M,wLow:d,wHigh:w,treatValue:v,controlValue:f};if(M==="mediate"){let R=He(),L=se=>Le(e,s,n,{treat:r,mediator:l,treatValue:v,controlValue:f,covariates:{[o]:se},sims:t.sims??1e3,confLevel:m,robustSE:t.robustSE??!1}),q=L(d);De(R);let W=L(w),he=W.dAvg.sims.map((se,vt)=>se-q.dAvg.sims[vt]),me=se=>({estimate:se.estimate,ci:se.ci,sims:se.sims});return{...h,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:y(W.dAvg.estimate-q.dAvg.estimate,he),low:q,high:W}}if(M!=="monteCarlo")throw new RangeError('method must be "monteCarlo" or "mediate"');let p=Math.trunc(t.nmc??2e4);if(!(p>=2))throw new RangeError("nmc must be at least 2");let N=t.robustSE?re(e,{type:"HC3"}):ne(e),b=t.robustSE?re(s,{type:"HC3"}):ne(s),g=(R,L)=>L.map(q=>{let W="family"in R?R.model.columnNames:R.coefNames;return R.coefficients[W.indexOf(q)]}),A=Ae(p,g(e,N.names),N.vcov),x=Ae(p,g(s,b.names),b.vcov),k=g(e,N.names),$=g(s,b.names),S=(R,L,q)=>{let W=q===void 0?R.indexOf(L):[`${L}:${q}`,`${q}:${L}`].map(he=>R.indexOf(he)).find(he=>he>=0)??-1;if(q===void 0&&W<0)throw new RangeError(`a model has no coefficient '${L}'`);return W},_=S(N.names,r),z=S(N.names,r,o),O=S(b.names,l),F=S(b.names,l,o),D=S(b.names,r),Q=S(b.names,r,o),V=(R,L)=>L<0?0:R[L],P=v-f,le=(R,L,q)=>P*(V(R,_)+V(R,z)*q)*(V(L,O)+V(L,F)*q),T=(R,L)=>P*(V(R,D)+V(R,Q)*L),C=R=>Array.from({length:p},(L,q)=>R(q)),I=C(R=>le(A[R],x[R],d)),U=C(R=>le(A[R],x[R],w)),G=C(R=>T(x[R],d)),Y=C(R=>T(x[R],w)),J=le(k,$,d),X=le(k,$,w),H=T($,d),j=T($,w);return{...h,indirectLow:y(J,I),indirectHigh:y(X,U),directLow:y(H,G),directHigh:y(j,Y),totalLow:y(J+H,I.map((R,L)=>R+G[L])),totalHigh:y(X+j,U.map((R,L)=>R+Y[L])),index:y(X-J,U.map((R,L)=>R-I[L]))}}export{Nt as balTab,Ft as johnsonNeyman,Et as match,Je as matchWeights,Le as mediate,Bt as mediationMonteCarlo,Jt as moderatedMediation,Wt as simSlopes,Ut as sobelTest,Rt as tableOneSmd,qt as trimWeights,Ht as weightSummary,_t 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};