@numero-uno-jpn/rstats 0.15.3 → 0.16.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 (285) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-VLUL2HFW.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.15.3 | 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{l as me,m as he,n as pe}from"./chunks/chunk-5ITR67MB.js";import"./chunks/chunk-USPEBXSR.js";import{A as Fe,B as je,C as Se,D as Te,E as _e,F as Ie,a as V,b as L,c as z,d as k,e as K,f as ge,g as de,j as ye,k as we,l as Y,m as be,n as Ne,o as Ee,p as Ae,q as Me,r as C,s as F,t as S,u as xe,v as $e,w as ve,x as Oe,y as Re,z as ke}from"./chunks/chunk-JQG3YQOC.js";import{a as ee,b as Le,c as Ce,d as Pe,e as Ue,f as qe}from"./chunks/chunk-MAUAOQG3.js";import"./chunks/chunk-IUULP3LE.js";import"./chunks/chunk-3WPU6LGK.js";import{a as G,e as I,f as J}from"./chunks/chunk-3THFTB36.js";import"./chunks/chunk-FCNVTIPJ.js";import{a as H}from"./chunks/chunk-HD73UKPT.js";import{b as _,c as X}from"./chunks/chunk-VLUL2HFW.js";import"./chunks/chunk-3TSWYE5L.js";import"./chunks/chunk-KT66SB7R.js";var B=4*Number.EPSILON,Ve={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function ze(e,n,t){let r=e.length,o=i=>e[Math.min(Math.max(i,1),r)-1];if(t===7){let i=1+(r-1)*n,h=Math.floor(i),m=o(h),y=o(Math.ceil(i));if(i>h&&y!==m){let g=i-h;return(1-g)*m+g*y}return m}let a,s;if(t<=3){let i=t===3?r*n-.5:r*n;a=Math.floor(i*(1+B)),t===1?s=i>a?1:0:t===2?s=i>a?1:.5:s=i!==a||Math.abs(a%2)===1?1:0}else{let[i,h]=Ve[t],m=i+n*(r+1-i-h);a=Math.floor(m*(1+B)),s=m-a,Math.abs(s)<B&&(s=0)}let l=o(a),f=o(a+1);return s===1?f:s>0&&s<1&&l!==f?(1-s)*l+s*f:l}function P(e,n=[0,.25,.5,.75,1],t={}){let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=Y(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let a=o.sort((i,h)=>i-h),s=typeof n=="number"?[n]:Array.from(n),l=100*Number.EPSILON;if(s.some(i=>i<-l||i>1+l))throw new RangeError("'probs' outside [0,1]");let f=s.map(i=>Number.isNaN(i)||a.length===0?NaN:ze(a,Math.min(Math.max(i,0),1),r));return typeof n=="number"?f[0]:f}function W(e,n={}){let[t,r]=P(e,[.25,.75],n);return r-t}function Be(e){let n=Array.from(e).filter(a=>!Number.isNaN(a)).sort((a,s)=>a-s),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(a=>.5*(n[Math.floor(a)-1]+n[Math.ceil(a)-1]))}function We(e,n={}){let t=Array.from(e),r=t.filter(m=>!Number.isNaN(m)),o=n.naRm?r:t,a=n.center??(o.length>r.length?NaN:F(r)),s=n.constant??1.4826,l=n.low??!1,f=n.high??!1,i=o.map(m=>Math.abs(m-a)),h=i.length;if((l||f)&&h%2===0){if(l&&f)throw new RangeError("'low' and 'high' cannot be both TRUE");let m=h/2+(f?1:0),y=i.filter(g=>!Number.isNaN(g)).sort((g,d)=>g-d);if(m===0||y.length<m)throw new RangeError(`'partial' index ${m} outside bounds`);return s*y[m-1]}return s*F(i)}var ne=e=>e===null||typeof e=="number"&&Number.isNaN(e),te=e=>Array.isArray(e)||ArrayBuffer.isView(e);function Ze(e){if(te(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function re(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(Ze),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,a)=>r.every(s=>!ne(s[a])))}function De(e){if(te(e))return Array.from(e).filter(r=>!ne(r));let n=re(e),t={};for(let[r,o]of Object.entries(e)){let a=Array.from(o).filter((s,l)=>n[l]);t[r]=o instanceof Float64Array?Float64Array.from(a):a}return t}function oe(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5;if(Number.isNaN(r)||Math.abs(r)>=2**31||Math.trunc(r)<0)throw new RangeError("invalid 'n' argument");let o=Math.trunc(r),a=n.minN??Math.floor(r/3);if(Number.isNaN(a)||Math.trunc(a)<0||Math.trunc(a)>o)throw new RangeError("invalid 'min.n' argument");let s=Math.trunc(a),l=n.shrinkSml??.75,f=n.highUBias??1.5,i=n.u5Bias??.5+1.5*f,h=1/0,m=-1/0;for(let A of t)A<h&&(h=A),A>m&&(m=A);let y=m-h,g,d;if(y===0&&m===0)g=1,d=!0;else{g=Math.max(Math.abs(h),Math.abs(m));let O=(1+(i>=1.5*f+.5?1/(1+f):1.5/(1+i)))*Math.max(1,o)*Number.EPSILON;d=y<g*O*3}d?(g>10&&(g=9+g/10),g*=l,s>1&&(g/=s)):(g=o>1?y/o:y,y===1/0&&o>=2&&(g=m/o-h/o));let x=2**-20*Qe;g<x?g=x:g>Number.MAX_VALUE/1.25&&(g=Number.MAX_VALUE/1.25);let b=10**Math.floor(Math.log10(g)),w=[[2*b,f],[5*b,i],[10*b,f]],c=b;for(let[A,O]of w)if(A-g<O*(g-c))c=A;else break;let u=1e-10,p=Math.floor(h/c+u);for(;p*c>h+u*c;)p--;for(;!Number.isFinite(p*c);)p++;let N=Math.ceil(m/c-u);for(;N*c<m-u*c;)N++;for(;!Number.isFinite(N*c);)N--;let E=Math.trunc(.5+N-p);if(E<s){let A=s-E,O=Math.floor(A/2),T=A%2;h===0&&p===0&&m!==0?N+=A:m===0&&N===0&&h!==0?p-=A:p>=0?(N+=O,p-=O+T):(p-=O,N+=O+T),E=s}let $=p*c<h?p*c:h,M=N*c>m?N*c:m;if(E<=0)return[$];let v;if(Number.isFinite(M-$))v=ee($,M,E+1);else{let A=M/E-$/E;v=Array.from({length:E+1},(O,T)=>$+T*A),v[E]=M}let R=M/E-$/E;return v.map(A=>Math.abs(A)<1e-14*R?0:A)}var Qe=22250738585072014e-324;function Ge(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function Je(e,n){let t=e.length,[r,o]=S(e),a=o-r;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let s=3.5*C(e)*t**-.3333333333333333;return s>0?Math.max(1,Math.ceil(a/s)):1}case"fd":case"freedman-diaconis":{let s=e.map(Ge),l=2*W(s);for(let f=1/8;l===0&&f>=1/512;f/=2){let[i,h]=P(s,[f,1-f]);l=(h-i)/(1-2*f)}return l===0&&(l=3.5*C(e)),l>0?Math.ceil(a/l*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Xe(e,n){let t=e.slice(1).map((r,o)=>r-e[o]);return e.length>5?F(t):e.length<=3?n:Math.min(...t.filter(r=>r>0))}function He(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,a=n.includeLowest??!0,s=n.breaks??"Sturges",l;if(typeof s!="string"&&typeof s!="number"&&s.length>1)l=[...s].sort((w,c)=>w-c);else{a=!0;let w=typeof s=="string"?Je(t,s):typeof s=="number"?s:s[0];if(!Number.isFinite(w)||w<1)throw new RangeError("invalid number of 'breaks'");w=Math.min(w,1e6);let[c,u]=S(t);l=oe([c,u],{n:w,minN:1});for(let p=1;p<l.length;p++)if(!(l[p]-l[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=l.length,[i,h]=r>0?S(t):[0,0],m=1e-7*Xe(l,h-i),y=l.map((w,c)=>o?c===0&&a?w-m:w+m:c<f-1?w-m:a?w+m:w-m),g=new Array(Math.max(0,f-1)).fill(0),d=0;for(let w of t){let c=Ke(w,y,o,a);c>=0&&(g[c]++,d++)}if(d<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let x=g.map((w,c)=>w/(r*(l[c+1]-l[c]))),b=g.map((w,c)=>.5*(l[c+1]+l[c]));return{breaks:l,counts:g,density:x,mids:b}}function Ke(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let l=1,f=o;for(;l<f;){let i=l+f>>1;e<=n[i]?f=i:l=i+1}return l-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let a=0,s=o-1;for(;a<s;){let l=a+s+1>>1;n[l]<=e?a=l:s=l-1}return a}function Ye(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,a=t;for(;o<a;){let s=o+a>>1;n[s]<=r?o=s+1:a=s}return o/t}}var U=e=>e===null||typeof e=="number"&&Number.isNaN(e),en=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?H(e,n):Number(e)-Number(n),nn=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?_(e):e>0?"Inf":"-Inf";function tn(e,n){let t=X(n),r=new Set(t.filter(l=>!U(l)).map(l=>typeof l));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let a=[...new Set(t.filter(l=>!U(l)))].sort(en),s=new Map(a.map((l,f)=>[l,f]));return{levels:a,codes:t.map(l=>U(l)?-1:s.get(l))}}var j=e=>Array.isArray(e)||e instanceof Float64Array;function ie(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(j))return[...e];if(e.some(j))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function Z(e,n,t){e.forEach((s,l)=>{if(s.length!==t)throw new RangeError(`${n[l]} must have one label per row (${t}), not ${s.length}`)});let r=e.map((s,l)=>tn(n[l],s)),o=r.reduce((s,l)=>s*l.levels.length,1),a=new Array(t);for(let s=0;s<t;s++){let l=0,f=1;for(let i of r){let h=i.codes[s];if(h<0){l=-1;break}l+=h*f,f*=i.levels.length}a[s]=l}return{factors:r,size:o,cells:a}}function D(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function rn(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var ce=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function on(e,n,t){let r=Array.from(e),o=ie(n),a=Z(o,ce(o.length,"index"),r.length),s=D(a).map(i=>i.length===0?null:{value:t(i.map(h=>r[h]))}),f=s.every(i=>i===null||typeof i.value=="number")?s.map(i=>i===null?NaN:i.value):s.map(i=>i===null?null:i.value);return{dim:a.factors.map(i=>i.levels.length),dimnames:a.factors.map(i=>[...i.levels]),values:f}}function sn(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=o instanceof Float64Array?Float64Array.from(n,a=>o[a]):n.map(a=>o[a]);return t}function ln(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!j(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function an(e,n,t={}){let r=t.sep??".",o=ie(n),a=!j(e);if(a&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let s=a?ln(e):e.length,l=Z(o,ce(o.length,"f"),s),f=a?[]:Array.from(e),i=new Map;return D(l).forEach((h,m)=>{if(h.length===0&&(t.drop||l.factors.length===1))return;let y=rn(l,m).map(nn).join(r);i.set(y,a?sn(e,h):h.map(g=>f[g]))}),i}function se(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!j(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function le(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new Error(`object '${n}' not found`);if(!j(t))throw new TypeError(`column '${n}' must be an array`);return t}function cn(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),{rhs:o}=G(`~ ${e.slice(t+1)}`),a=/^[A-Za-z.][A-Za-z0-9._]*$/,s;if(r!=="."){let i=/^cbind\s*\((.*)\)$/s.exec(r);if(s=i===null?[r]:i[1].split(",").map(h=>h.trim()),s.some(h=>!a.test(h)||h==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(I(o,[]).length<I(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let l=s===void 0?[]:n.filter(i=>!s.includes(i)),f=I(o,l);return J(o,()=>0,l),{values:s??n.filter(i=>!f.includes(i)),groups:f}}function ae(e,n,t,r,o,a){let s=r[0]?.length??n[0]?.length??0;e.forEach((h,m)=>{if(n[m].length!==s)throw new RangeError(`variable lengths differ (found for '${h}')`)});let l=Z(r,t,s),f=D(l).map((h,m)=>({cell:m,rows:h.filter(o)})).filter(h=>h.rows.length>0),i={};return t.forEach((h,m)=>{let y=r[m];i[h]=f.map(g=>{let d=y[g.rows[0]];return d===0?0:d})}),e.forEach((h,m)=>{let y=n[m],d=f.map(b=>a(b.rows.map(w=>y[w]))).map(b=>{if(typeof b=="number")return{names:void 0,values:[b]};if(Array.isArray(b))return{names:void 0,values:[...b]};let w=b;return{names:Object.keys(w),values:Object.values(w)}}),x=d[0]?.values.length??1;if(d.some(b=>b.values.length!==x))throw new RangeError("fun must return values of the same length for every group");if(x===1&&d[0]?.names===void 0){i[h]=d.map(b=>b.values[0]);return}for(let b=0;b<x;b++){let w=d[0].names?.[b]??String(b+1);i[`${h}.${w}`]=d.map(c=>c.values[b])}}),i}function un(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let l=n,{values:f,groups:i}=cn(e,Object.keys(l)),h=d=>Object.prototype.hasOwnProperty.call(l,d),m=f.map(d=>se(d,h(d)?l[d]:void 0)),y=i.map(d=>le(l,d));return ae(f,m,i,y,d=>m.every(x=>!Number.isNaN(x[d]))&&y.every(x=>!U(x[d])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(l=>se(l,e[l])),a=Object.keys(n);if(a.length===0)throw new RangeError("'by' must name at least one grouping column");let s=a.map(l=>le(n,l));return ae(r,o,a,s,()=>!0,t)}var q=e=>typeof e=="string"?[e]:[...e];function fe(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function fn(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function mn(e,n){let t=null;for(let r of n){let o=fn(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function hn(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new Error(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(a=>{let s=o.exec(a);return Array.from({length:t},(l,f)=>s===null?null:s[f+1]??null)})}function pn(e,n,t,r){let o=new RegExp(n,"g"),a=[],s=[],l=e.map((i,h)=>{let m=[],y=0;for(let g of i.matchAll(o))g[0].length!==0&&(m.push(i.slice(y,g.index)),y=g.index+g[0].length);return m.push(i.slice(y)),m.length>t&&a.push(h+1),m.length<t&&s.push(h+1),Array.from({length:t},(g,d)=>m[d]??null)}),f=i=>`${i.length} rows [${i.join(", ")}]`;return a.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(a)}.`),s.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(s)}.`),l}function gn(e,n,t,r){let{namesSep:o,namesPattern:a}=t;if(n.length===1){if(o!==void 0)throw new Error("`names_sep` can't be used with a length 1 `names_to`.");if(a===void 0)return e.map(l=>[l]);let s=new RegExp(a);return e.map(l=>[s.exec(l)?.[1]??null])}if(o===void 0==(a===void 0))throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?pn(e,o,n.length,r):hn(e,a,n.length)}function dn(e,n){let t=V(e),r=Object.keys(e),o=typeof n.cols=="function"?r.filter(n.cols):[...new Set(n.cols)];if(fe(e,o),o.length===0)throw new Error("`cols` must select at least one column.");let a=q(n.namesTo??"name"),s=a.indexOf(".value");if(a.lastIndexOf(".value")!==s)throw new Error('`names_to` may contain ".value" only once');let l=[],f=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),i=o.map(c=>f===null?c:c.replace(f,"")),h=gn(i,a,n,l),m=[],y=[];if(s<0)m.push(...h),y.push({name:n.valuesTo??"value",sources:[...o]});else{let c=new Map,u=new Map;h.forEach((p,N)=>{let E=p.filter((A,O)=>O!==s),$=JSON.stringify(E),M=c.get($);if(M===void 0){M=m.length,c.set($,M),m.push(E);for(let A of y)A.sources.push(null)}let v=p[s]??"NA",R=u.get(v);if(R===void 0&&(R={name:v,sources:m.map(()=>null)},u.set(v,R),y.push(R)),R.sources[M]!==null)throw new Error(`the names give the value column '${v}' twice for one key`);R.sources[M]=o[N]})}let g=y.map(c=>mn(e,c.sources.filter(u=>u!==null))),d=[];if(n.colsVary==="slowest")for(let c=0;c<m.length;c++)for(let u=0;u<t;u++)d.push([u,c]);else for(let c=0;c<t;c++)for(let u=0;u<m.length;u++)d.push([c,u]);let x=(c,u,p)=>{let N=c.sources[p];return N==null?null:e[N][u]};n.valuesDropNa===!0&&(d=d.filter(([c,u])=>y.some(p=>!L(x(p,c,u)))));let b={},w=d.map(([c])=>c);for(let c of r)o.includes(c)||k(b,c,z(e[c],w));if(a.forEach((c,u)=>{if(u===s)return;let p=n.namesTransform?.[c],N=E=>{let $=m[E][u<s||s<0?u:u-1];return $===null||p===void 0?$:p($)};k(b,c,d.map(([,E])=>N(E)))}),y.forEach((c,u)=>{let p=g[u]==="double";if(p&&c.sources.every(N=>N!==null&&e[N]instanceof Float64Array))k(b,c.name,Float64Array.from(d,([N,E])=>x(c,N,E)));else{let N=d.map(([E,$])=>{let M=x(c,E,$);return p&&typeof M=="boolean"?Number(M):M});k(b,c.name,N)}}),n.onWarning!==void 0)for(let c of new Set(l))n.onWarning(c);return b}var yn=e=>L(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function ue(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(a,s)=>{let l=JSON.stringify(e.map(i=>yn(i[s]))),f=t.get(l);return f===void 0&&(f=r.length,t.set(l,f),r.push(s)),f}),firsts:r}}function wn(e){return L(e)?"NA":typeof e=="number"?Number.isFinite(e)?_(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function Q(e,n,t){if(e!==void 0)return n(e)?e:e[t]}function bn(e,n={}){let t=V(e),r=q(n.namesFrom??"name"),o=q(n.valuesFrom??"value"),a=n.idCols===void 0?Object.keys(e).filter(u=>!r.includes(u)&&!o.includes(u)):q(n.idCols);fe(e,[...a,...r,...o]);let s=n.namesPrefix??"",l=n.namesSep??"_",f=ue(a.map(u=>e[u]),t),i=ue(r.map(u=>e[u]),t),h=i.firsts.map((u,p)=>p);n.namesSort===!0&&h.sort((u,p)=>{for(let N of r){let E=K(e[N][i.firsts[u]],e[N][i.firsts[p]]);if(E!==0)return E}return 0});let m=i.firsts.map(u=>s+r.map(p=>wn(e[p][u])).join(l)),y=i.firsts.length,g=Array.from({length:f.firsts.length*y},()=>[]);for(let u=0;u<t;u++)g[f.codes[u]*y+i.codes[u]].push(u);let d=u=>typeof u=="function",x=u=>typeof u!="object"||u===null,b=(u,p)=>{let N=e[u],E=Q(n.valuesFn,d,u),$=Q(n.valuesFill,x,u)??null,M=f.firsts.map((v,R)=>{let A=g[R*y+p];return A.length===0?$:E!==void 0?E(A.map(O=>N[O])):N[A[0]]});return N instanceof Float64Array&&M.every(v=>v===null||typeof v=="number")?Float64Array.from(M,v=>v===null?NaN:v):M};for(let u of o)if(Q(n.valuesFn,d,u)===void 0&&g.some(p=>p.length>1))throw new Error(`values from '${u}' are not uniquely identified; use valuesFn to summarise them`);let w={};for(let u of a)k(w,u,z(e[u],f.firsts));let c=(u,p)=>o.length===1?m[p]:`${u}${l}${m[p]}`;if(n.namesVary==="slowest")for(let u of h)for(let p of o)k(w,c(p,u),b(p,u));else for(let u of o)for(let p of h)k(w,c(u,p),b(u,p));return w}export{W as IQR,un as aggregate,re as completeCases,pe as cor,he as cov,ve as cummax,Oe as cummin,$e as cumprod,xe as cumsum,Ue as cut,_e as cv,Re as diff,Ye as ecdf,qe as findInterval,Be as fivenum,ye as fromRows,je as geometricMean,He as hist,Fe as kurtosis,We as mad,Ee as mean,Te as meanAD,F as median,ge as merge,Se as modes,De as naOmit,dn as pivotLonger,bn as pivotWider,oe as pretty,Ne as prod,P as quantile,S as range,me as rank,Ie as scale,C as sd,ke as skewness,an as split,de as subset,be as sum,Ce as table,Le as tabulate,on as tapply,we as toRows,Pe as unique,Me as variance,Ae as weightedMean};
1
+ /*! rStats.js 0.16.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{m as Oe,n as Re,o as ke}from"./chunks/chunk-BG2KLEHM.js";import"./chunks/chunk-ZGABZMWX.js";import{A as We,B as Ze,C as Qe,D as Ge,E as Je,F as Xe,a as G,b as B,c as J,d as F,e as ue,f as Fe,g as Te,j as je,k as Ce,l as ce,m as _e,n as Se,o as Ie,p as Le,q as Pe,r as D,s as _,t as S,u as Ue,v as Ve,w as qe,x as ze,y as Be,z as De}from"./chunks/chunk-VTUGG2SV.js";import{a as fe,b as He,c as Ke,d as Ye,e as en,f as nn}from"./chunks/chunk-KAZRWIB5.js";import"./chunks/chunk-SYWOBOTR.js";import{a as se,e as z,f as le}from"./chunks/chunk-FLJNSXSW.js";import"./chunks/chunk-72Y3HZID.js";import{a as ae}from"./chunks/chunk-QNNL7AZ3.js";import{b as q,c as ie}from"./chunks/chunk-YRZWONZB.js";import{b as V,c as oe}from"./chunks/chunk-W26LRYOJ.js";import"./chunks/chunk-SC6CV4Z3.js";import{N as Q,s as P}from"./chunks/chunk-GM53LWSR.js";var X=4*Number.EPSILON,tn={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function rn(e,n,t){let r=e.length,o=a=>e[Math.min(Math.max(a,1),r)-1];if(t===7){let a=1+(r-1)*n,m=Math.floor(a),u=o(m),p=o(Math.ceil(a));if(a>m&&p!==u){let h=a-m;return(1-h)*u+h*p}return u}let i,s;if(t<=3){let a=t===3?r*n-.5:r*n;i=Math.floor(a*(1+X)),t===1?s=a>i?1:0:t===2?s=a>i?1:.5:s=a!==i||Math.abs(i%2)===1?1:0}else{let[a,m]=tn[t],u=a+n*(r+1-a-m);i=Math.floor(u*(1+X)),s=u-i,Math.abs(s)<X&&(s=0)}let l=o(i),f=o(i+1);return s===1?f:s>0&&s<1&&l!==f?(1-s)*l+s*f:l}function W(e,n=[0,.25,.5,.75,1],t={}){let r=t.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let o=ce(e,t.naRm);if(o===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let i=o.sort((a,m)=>a-m),s=typeof n=="number"?[n]:Array.from(n),l=100*Number.EPSILON;if(s.some(a=>a<-l||a>1+l))throw new RangeError("'probs' outside [0,1]");let f=s.map(a=>Number.isNaN(a)||i.length===0?NaN:rn(i,Math.min(Math.max(a,0),1),r));return typeof n=="number"?f[0]:f}function H(e,n={}){let[t,r]=W(e,[.25,.75],n);return r-t}function on(e){let n=Array.from(e).filter(i=>!Number.isNaN(i)).sort((i,s)=>i-s),t=n.length;if(t===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((t+3)/2)/2;return[1,r,(t+1)/2,t+1-r,t].map(i=>V(n[Math.floor(i)-1],n[Math.ceil(i)-1]))}function sn(e,n={}){let t=Array.from(e),r=t.filter(u=>!Number.isNaN(u)),o=n.naRm?r:t,i=n.center??(o.length>r.length?NaN:_(r)),s=n.constant??1.4826,l=n.low??!1,f=n.high??!1,a=o.map(u=>Math.abs(u-i)),m=a.length;if((l||f)&&m%2===0){if(l&&f)throw new RangeError("'low' and 'high' cannot be both TRUE");let u=m/2+(f?1:0),p=a.filter(h=>!Number.isNaN(h)).sort((h,N)=>h-N);if(u===0||p.length<u)throw new RangeError(`'partial' index ${u} outside bounds`);return s*p[u-1]}return s*_(a)}var me=e=>e===null||typeof e=="number"&&Number.isNaN(e),he=e=>Array.isArray(e)||ArrayBuffer.isView(e);function ln(e){if(he(e))return{columns:[e],rows:e.length};if(typeof e!="object"||e===null)throw new TypeError("the arguments must be arrays or data frames");let n=Object.values(e),t=n[0]?.length??0;if(n.some(r=>r.length!==t))throw new RangeError("not all arguments have the same length");return{columns:n,rows:t}}function pe(...e){if(e.length===0)throw new RangeError("no input has determined the number of cases");let n=e.map(ln),t=n[0].rows;if(n.some(o=>o.rows!==t))throw new RangeError("not all arguments have the same length");let r=n.flatMap(o=>o.columns);return Array.from({length:t},(o,i)=>r.every(s=>!me(s[i])))}function an(e){if(he(e))return Array.from(e).filter(r=>!me(r));let n=pe(e),t={};for(let[r,o]of Object.entries(e)){let i=Array.from(o).filter((s,l)=>n[l]);F(t,r,o instanceof Float64Array?Float64Array.from(i):i)}return t}function ge(e,n={}){let t=Array.from(e).filter(Number.isFinite);if(t.length===0)return[];let r=n.n??5;if(Number.isNaN(r)||Math.abs(r)>=2**31||Math.trunc(r)<0)throw new RangeError("invalid 'n' argument");let o=Math.trunc(r),i=n.minN??Math.floor(r/3);if(Number.isNaN(i)||Math.trunc(i)<0||Math.trunc(i)>o)throw new RangeError("invalid 'min.n' argument");let s=Math.trunc(i),l=n.shrinkSml??.75;if(!Number.isFinite(l)||l<=0)throw new RangeError("invalid 'shrink.sml' argument");let f=n.highUBias??1.5;if(!Number.isFinite(f)||f<0)throw new RangeError("invalid 'high.u.bias' argument");let a=n.u5Bias??.5+1.5*f;if(!Number.isFinite(a)||a<0)throw new RangeError("invalid 'u5.bias' argument");let m=1/0,u=-1/0;for(let $ of t)$<m&&(m=$),$>u&&(u=$);let p=u-m,h,N;if(p===0&&u===0)h=1,N=!0;else{h=Math.max(Math.abs(m),Math.abs(u));let M=(1+(a>=1.5*f+.5?1/(1+f):1.5/(1+a)))*Math.max(1,o)*Number.EPSILON;N=p<h*M*3}N?(h>10&&(h=9+h/10),h*=l,s>1&&(h/=s)):(h=o>1?p/o:p,p===1/0&&o>=2&&(h=u/o-m/o));let E=2**-20*un;h<E?h=E:h>Number.MAX_VALUE/1.25&&(h=Number.MAX_VALUE/1.25);let O=10**Math.floor(Math.log10(h)),g=[[2*O,f],[5*O,a],[10*O,f]],y=O;for(let[$,M]of g)if($-h<M*(h-y))y=$;else break;let d=1e-10,w=Math.floor(m/y+d);for(;w*y>m+d*y;)w--;for(;!Number.isFinite(w*y);)w++;let x=Math.ceil(u/y-d);for(;x*y<u-d*y;)x++;for(;!Number.isFinite(x*y);)x--;let c=Math.trunc(.5+x-w);if(c<s){let $=s-c,M=Math.floor($/2),k=$%2;m===0&&w===0&&u!==0?x+=$:u===0&&x===0&&m!==0?w-=$:w>=0?(x+=M,w-=M+k):(w-=M,x+=M+k),c=s}let b=w*y<m?w*y:m,A=x*y>u?x*y:u;if(c<=0)return[b];let R=fe(b,A,c+1),v=A/c-b/c;return R.map($=>Math.abs($)<1e-14*v?0:$)}var un=22250738585072014e-324;function cn(e){return e===0||!Number.isFinite(e)?e:Number(e.toPrecision(5))}function fn(e,n){let t=e.length;switch(n.toLowerCase()){case"sturges":return Math.ceil(Math.log2(t)+1);case"scott":{let r=l=>[S(l),3.5*D(l)*t**-.3333333333333333],[[o,i],s]=r(e);return Number.isFinite(i-o)&&Number.isFinite(s)||([[o,i],s]=r(Q([e]).groups[0])),s>0?Math.max(1,Math.ceil((i-o)/s)):1}case"fd":case"freedman-diaconis":{let r=(f,a)=>{let m=2*H(a);for(let u=.125;m===0&&u>=.001953125;u/=2){let[p,h]=W(a,[u,1-u]);m=(h-p)/(1-2*u)}return m===0&&(m=3.5*D(f)),[S(f),m]},o=e.map(cn),[[i,s],l]=r(e,o);if(!(Number.isFinite(s-i)&&Number.isFinite(l))){let{k:f}=Q([e]);[[i,s],l]=r(e.map(a=>P(a,-f)),o.map(a=>P(a,-f)))}return l>0?Math.ceil((s-i)/l*t**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function mn(e,n,t){let r=e.slice(1).map((o,i)=>o-e[i]);return e.length>5?1e-7*_(r):e.length<=3?t-n===1/0?2*(1e-7*(t/2-n/2)):1e-7*(t-n):1e-7*oe(r.filter(o=>o>0))}function hn(e,n={}){let t=Array.from(e).filter(Number.isFinite),r=t.length,o=n.right??!0,i=n.includeLowest??!0,s=n.breaks??"Sturges",l;if(typeof s!="string"&&typeof s!="number"&&s.length>1){if(!s.every(Number.isFinite))throw new RangeError("'breaks' are not finite");if(l=[...s].sort((g,y)=>g-y),l.some((g,y)=>y>0&&!(g>l[y-1])))throw new RangeError("'breaks' are not strictly increasing")}else{i=!0;let g=typeof s=="string"?fn(t,s):typeof s=="number"?s:s[0];if(!Number.isFinite(g)||g<1)throw new RangeError("invalid number of 'breaks'");g=Math.min(g,1e6);let[y,d]=S(t);l=ge([y,d],{n:g,minN:1});for(let w=1;w<l.length;w++)if(!(l[w]-l[w-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let f=l.length,[a,m]=r>0?S(t):[0,0],u=mn(l,a,m),p=l.map((g,y)=>o?y===0&&i?g-u:g+u:y<f-1?g-u:i?g+u:g-u),h=new Array(Math.max(0,f-1)).fill(0),N=0;for(let g of t){let y=gn(g,p,o,i);y>=0&&(h[y]++,N++)}if(N<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let E=h.map((g,y)=>pn(g,r,l[y],l[y+1])),O=h.map((g,y)=>V(l[y+1],l[y]));return{breaks:l,counts:h,density:E,mids:O}}function pn(e,n,t,r){let o=r-t;if(!(n*o===1/0&&Number.isFinite(t)&&Number.isFinite(r)))return e/(n*o);let i=o===1/0?1:0,s=i===1?r/2-t/2:o,l=Math.floor(Math.log2(s));return P(e,-(l+i))/(n*P(s,-l))}function gn(e,n,t,r){let o=n.length-1;if(o<1)return-1;if(t){if(e===n[0]&&r)return 0;if(!(e>n[0]&&e<=n[o]))return-1;let l=1,f=o;for(;l<f;){let a=Math.floor((l+f)/2);e<=n[a]?f=a:l=a+1}return l-1}if(e===n[o]&&r)return o-1;if(!(e>=n[0]&&e<n[o]))return-1;let i=0,s=o-1;for(;i<s;){let l=Math.floor((i+s+1)/2);n[l]<=e?i=l:s=l-1}return i}function dn(e){let n=Array.from(e).filter(r=>!Number.isNaN(r)).sort((r,o)=>r-o),t=n.length;if(t<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let o=0,i=t;for(;o<i;){let s=Math.floor((o+i)/2);n[s]<=r?o=s+1:i=s}return o/t}}var Z=e=>e===null||typeof e=="number"&&Number.isNaN(e),wn=(e,n)=>typeof e=="number"?e-n:typeof e=="string"?ae(e,n):Number(e)-Number(n),yn=e=>typeof e=="boolean"?e?"TRUE":"FALSE":typeof e=="string"?e:Number.isFinite(e)?q(e):e>0?"Inf":"-Inf";function bn(e,n){let t=ie(n),r=new Set(t.filter(l=>!Z(l)).map(l=>typeof l));if(r.size>1)throw new TypeError(`${e} mixes ${[...r].join(" and ")} labels`);let o=[...r][0];if(o!==void 0&&o!=="number"&&o!=="string"&&o!=="boolean")throw new TypeError(`${e} has labels of an unsupported type`);let i=[...new Set(t.filter(l=>!Z(l)))].sort(wn),s=new Map(i.map((l,f)=>[l,f]));return{levels:i,codes:t.map(l=>Z(l)?-1:s.get(l))}}var I=e=>Array.isArray(e)||e instanceof Float64Array;function be(e){if(e instanceof Float64Array)return[e];if(!Array.isArray(e))throw new TypeError("the group labels must be an array or an array of arrays");if(e.length>0&&e.every(I))return[...e];if(e.some(I))throw new TypeError("the group labels must be an array or an array of arrays");return[e]}function K(e,n,t){e.forEach((s,l)=>{if(s.length!==t)throw new RangeError(`${n[l]} must have one label per row (${t}), not ${s.length}`)});let r=e.map((s,l)=>bn(n[l],s)),o=r.reduce((s,l)=>s*l.levels.length,1);if(o>=2**31)throw new RangeError("total number of levels >= 2^31");let i=new Array(t);for(let s=0;s<t;s++){let l=0,f=1;for(let a of r){let m=a.codes[s];if(m<0){l=-1;break}l+=m*f,f*=a.levels.length}i[s]=l}return{factors:r,size:o,cells:i}}function Y(e){let n=Array.from({length:e.size},()=>[]);return e.cells.forEach((t,r)=>{t>=0&&n[t].push(r)}),n}function Nn(e,n){return e.factors.map(t=>{let r=t.levels.length,o=t.levels[n%r];return n=Math.floor(n/r),o})}var Ne=(e,n)=>Array.from({length:e},(t,r)=>e===1?n:`${n}[${r}]`);function En(e,n,t){let r=Array.from(e),o=be(n),i=K(o,Ne(o.length,"index"),r.length),s=Y(i).map(a=>a.length===0?null:{value:t(a.map(m=>r[m]))}),f=s.every(a=>a===null||typeof a.value=="number")?s.map(a=>a===null?NaN:a.value):s.map(a=>a===null?null:a.value);return{dim:i.factors.map(a=>a.levels.length),dimnames:i.factors.map(a=>[...a.levels]),values:f}}function xn(e,n){let t={};for(let[r,o]of Object.entries(e))F(t,r,o instanceof Float64Array?Float64Array.from(n,i=>o[i]):n.map(i=>o[i]));return t}function $n(e){let t=Object.values(e)[0]?.length??0;for(let[r,o]of Object.entries(e)){if(!I(o))throw new TypeError(`column '${r}' must be an array`);if(o.length!==t)throw new RangeError(`the columns of the data frame have different lengths (found for '${r}')`)}return t}function An(e,n,t={}){let r=t.sep??".",o=be(n),i=!I(e);if(i&&(typeof e!="object"||e===null))throw new TypeError("x must be an array or a data frame");let s=i?$n(e):e.length,l=K(o,Ne(o.length,"f"),s),f=i?[]:Array.from(e),a=new Map;return Y(l).forEach((m,u)=>{if(m.length===0&&(t.drop||l.factors.length===1))return;let p=Nn(l,u).map(yn).join(r);if(a.has(p))throw new RangeError(`the group names joined with '${r}' are not unique ('${p}'); use another sep`);a.set(p,i?xn(e,m):m.map(h=>f[h]))}),a}function de(e,n){if(n===void 0)throw new Error(`object '${e}' not found`);if(!I(n))throw new TypeError(`column '${e}' must be an array`);return Array.from(n,t=>{if(t===null)return NaN;if(typeof t!="number")throw new TypeError(`column '${e}' to summarise must be numeric`);return t})}function we(e,n){let t=Object.prototype.hasOwnProperty.call(e,n)?e[n]:void 0;if(t===void 0)throw new Error(`object '${n}' not found`);if(!I(t))throw new TypeError(`column '${n}' must be an array`);return t}function Mn(e,n){if(typeof e!="string")throw new TypeError("the formula must be a string");let t=e.indexOf("~");if(t<0)throw new SyntaxError("invalid formula: missing '~'");let r=e.slice(0,t).trim(),{rhs:o}=se(`~ ${e.slice(t+1)}`),i=/^[A-Za-z.][A-Za-z0-9._]*$/,s;if(r!=="."){let a=/^cbind\s*\((.*)\)$/s.exec(r);if(s=a===null?[r]:a[1].split(",").map(m=>m.trim()),s.some(m=>!i.test(m)||m==="."))throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'")}else if(z(o,[]).length<z(o,["."]).length)throw new SyntaxError("invalid formula: '.' cannot be on both sides");let l=s===void 0?[]:n.filter(a=>!s.includes(a)),f=z(o,l);return le(o,()=>0,l),{values:s??n.filter(a=>!f.includes(a)),groups:f}}function ye(e,n,t,r,o,i){let s=r[0]?.length??n[0]?.length??0;e.forEach((u,p)=>{if(n[p].length!==s)throw new RangeError(`variable lengths differ (found for '${u}')`)});let l=K(r,t,s),f=Y(l).map((u,p)=>({cell:p,rows:u.filter(o)})).filter(u=>u.rows.length>0),a={};t.forEach((u,p)=>{let h=r[p];F(a,u,f.map(N=>{let E=h[N.rows[0]];return E===0?0:E}))});let m=(u,p)=>{if(Object.hasOwn(a,u))throw new RangeError(`duplicate column name '${u}' in the result`);F(a,u,p)};return e.forEach((u,p)=>{let h=n[p],E=f.map(g=>i(g.rows.map(y=>h[y]))).map(g=>{if(typeof g=="number")return{names:void 0,values:[g]};if(Array.isArray(g))return{names:void 0,values:[...g]};let y=g;return{names:Object.keys(y),values:Object.values(y)}}),O=E[0]?.values.length??1;if(E.some(g=>g.values.length!==O))throw new RangeError("fun must return values of the same length for every group");if(O===1&&E[0]?.names===void 0){m(u,E.map(g=>g.values[0]));return}for(let g=0;g<O;g++){let y=E[0].names?.[g]??String(g+1);m(`${u}.${y}`,E.map(d=>d.values[g]))}}),a}function vn(e,n,t){if(typeof n!="object"||n===null)throw new TypeError("the data must be an object of columns");if(typeof e=="string"){let l=n,{values:f,groups:a}=Mn(e,Object.keys(l)),m=N=>Object.prototype.hasOwnProperty.call(l,N),u=f.map(N=>de(N,m(N)?l[N]:void 0)),p=a.map(N=>we(l,N));return ye(f,u,a,p,N=>u.every(E=>!Number.isNaN(E[N]))&&p.every(E=>!Z(E[N])),t)}if(typeof e!="object"||e===null)throw new TypeError("x must be a data frame");let r=Object.keys(e),o=r.map(l=>de(l,e[l])),i=Object.keys(n);if(i.length===0)throw new RangeError("'by' must name at least one grouping column");let s=i.map(l=>we(n,l));return ye(r,o,i,s,()=>!0,t)}var ne=e=>typeof e=="string"?[e]:[...e];function Ae(e,n){if(n==null)return"fastest";if(n==="fastest"||n==="slowest")return n;throw typeof n!="string"?new Error(`\`${e}\` must be a string or character vector.`):new Error(`\`${e}\` must be one of "fastest" or "slowest", not "${n}".`)}function te(e,n){for(let t of n)if(!Object.hasOwn(e,t))throw new Error(`Column \`${t}\` doesn't exist.`)}function Me(e,n){if(n instanceof Float64Array)return"double";let t=null;for(let r of n){if(r===null)continue;let o=typeof r=="number"?"double":typeof r=="string"?"character":"logical";if(t!==null&&o!==t)throw new TypeError(`column '${e}' mixes ${t} and ${o} values`);t=o}return t}function On(e,n){let t=null;for(let r of n){let o=Me(r,e[r]);if(o!==null){if(t===null)t={type:o,column:r};else if(t.type!==o){if(t.type==="character"||o==="character")throw new TypeError(`Can't combine \`${t.column}\` <${t.type}> and \`${r}\` <${o}>.`);o==="double"&&(t={type:o,column:r})}}}return t?.type??null}function Ee(e,n,t){let r=new RegExp(`${n}|`).exec("").length-1;if(r!==t)throw new Error(`\`regex\` should define ${t} groups; ${r} found.`);let o=new RegExp(n);return e.map(i=>{let s=o.exec(i);return Array.from({length:t},(l,f)=>s===null?null:s[f+1]??null)})}function Rn(e,n){let t=e.charCodeAt(n);if(t>=55296&&t<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);if(r>=56320&&r<=57343)return 2}return 1}function kn(e,n,t,r){let o=new RegExp(n,"g"),i=[],s=[],l=e.map((a,m)=>{let u=[],p=0,h=0;for(;;){o.lastIndex=p;let N=o.exec(a);if(N===null||(u.push(a.slice(h,N.index)),h=N.index+N[0].length,p=N[0].length===0?N.index+Rn(a,N.index):h,p>=a.length))break}return u.push(a.slice(h)),u.length>t&&i.push(m+1),u.length<t&&s.push(m+1),Array.from({length:t},(N,E)=>u[E]??null)}),f=a=>`${a.length} rows [${a.join(", ")}]`;return i.length>0&&r.push(`Expected ${t} pieces. Additional pieces discarded in ${f(i)}.`),s.length>0&&r.push(`Expected ${t} pieces. Missing pieces filled with \`NA\` in ${f(s)}.`),l}function xe(e,n){return e!==void 0&&Object.hasOwn(e,n)?e[n]:void 0}function Fn(e,n,t,r){let{namesSep:o,namesPattern:i}=t;if(n.length===0)return e.map(()=>[]);if(n.length===1){if(o!==void 0)throw new Error("`names_sep` can't be used with a length 1 `names_to`.");return i===void 0?e.map(s=>[s]):Ee(e,i,1)}if(o===void 0==(i===void 0))throw new Error("If you supply multiple names in `names_to` you must also supply one of `names_sep` or `names_pattern`.");return o!==void 0?kn(e,o,n.length,r):Ee(e,i,n.length)}function Tn(e,n){let t=Ae("cols_vary",n.colsVary),r=G(e),o=Object.keys(e),i=typeof n.cols=="function"?o.filter(n.cols):[...new Set(n.cols)];if(te(e,i),i.length===0)throw new Error("`cols` must select at least one column.");let s=ne(n.namesTo??"name"),l=s.indexOf(".value");if(s.lastIndexOf(".value")!==l)throw new Error('`names_to` may contain ".value" only once');let f=[],a=n.namesPrefix===void 0?null:new RegExp(`^(?:${n.namesPrefix})`),m=i.map(d=>a===null?d:d.replace(a,"")),u=Fn(m,s,n,f),p=[],h=[];if(l<0)p.push(...u),h.push({name:n.valuesTo??"value",sources:[...i]});else{let d=new Map,w=new Map,x=xe(n.namesTransform,".value");u.forEach((c,b)=>{let A=c.filter((j,C)=>C!==l),R=JSON.stringify(A),v=d.get(R);if(v===void 0){v=p.length,d.set(R,v),p.push(A);for(let j of h)j.sources.push(null)}let $=c[l]??null,M=$===null||x===void 0?$:x($);if(M!==null&&typeof M!="string")throw new Error(`the transform of \`.value\` must give strings, not ${typeof M}`);let k=M??"NA",T=w.get(k);if(T===void 0&&(T={name:k,sources:p.map(()=>null)},w.set(k,T),h.push(T)),T.sources[v]!==null)throw new Error(`the names give the value column '${k}' twice for one key`);T.sources[v]=i[b]})}let N=h.map(d=>On(e,d.sources.filter(w=>w!==null))),E=[];if(t==="slowest")for(let d=0;d<p.length;d++)for(let w=0;w<r;w++)E.push([w,d]);else for(let d=0;d<r;d++)for(let w=0;w<p.length;w++)E.push([d,w]);let O=(d,w,x)=>{let c=d.sources[x];return c==null?null:e[c][w]};n.valuesDropNa===!0&&(E=E.filter(([d,w])=>h.some(x=>!B(O(x,d,w)))));let g={},y=E.map(([d])=>d);for(let d of o)i.includes(d)||F(g,d,J(e[d],y));if(s.forEach((d,w)=>{if(w===l)return;let x=xe(n.namesTransform,d),c=b=>{let A=p[b][w<l||l<0?w:w-1];return A===null||x===void 0?A:x(A)};F(g,d,E.map(([,b])=>c(b)))}),h.forEach((d,w)=>{let x=N[w]==="double";if(x&&d.sources.every(c=>c!==null&&e[c]instanceof Float64Array))F(g,d.name,Float64Array.from(E,([c,b])=>O(d,c,b)));else{let c=E.map(([b,A])=>{let R=O(d,b,A);return x&&typeof R=="boolean"?Number(R):R});F(g,d.name,c)}}),n.onWarning!==void 0)for(let d of new Set(f))n.onWarning(d);return g}var re=e=>typeof e=="number"?"double":typeof e=="string"?"character":"logical";function jn(e,n){if(e===null||n===null)return e;let t=re(e);if(t===n)return e;if(n==="double"&&t==="logical")return Number(e);if(n==="logical"&&t==="double"){let r=e;if(Number.isNaN(r))return null;if(r===0||r===1)return r===1;throw new TypeError("Can't convert from `fill` <double> to <logical> due to loss of precision.")}throw new TypeError(`Can't convert \`fill\` <${t}> to <${n}>.`)}var Cn=e=>B(e)?"NA":typeof e=="number"?`n${e}`:typeof e=="string"?`s${e}`:`b${String(e)}`;function $e(e,n){let t=new Map,r=[];return{codes:Array.from({length:n},(i,s)=>{let l=JSON.stringify(e.map(a=>Cn(a[s]))),f=t.get(l);return f===void 0&&(f=r.length,t.set(l,f),r.push(s)),f}),firsts:r}}function _n(e){return B(e)?"NA":typeof e=="number"?Number.isFinite(e)?q(e):e>0?"Inf":"-Inf":typeof e=="boolean"?e?"TRUE":"FALSE":e}function ee(e,n,t){if(e!==void 0)return n(e)?e:Object.hasOwn(e,t)?e[t]:void 0}function Sn(e,n={}){let t=Ae("names_vary",n.namesVary),r=G(e),o=(c,b)=>{let A=[...new Set(ne(c))];if(te(e,A),A.length===0)throw new Error(`\`${b}\` must select at least one column.`);return A},i=o(n.namesFrom??"name","names_from"),s=o(n.valuesFrom??"value","values_from"),l=n.idCols===void 0?Object.keys(e).filter(c=>!i.includes(c)&&!s.includes(c)):[...new Set(ne(n.idCols))];te(e,l);for(let c of l){let b=i.includes(c)?"names_from":s.includes(c)?"values_from":null;if(b!==null)throw new Error(`\`id_cols\` can't select a column already selected by \`${b}\`. Column \`${c}\` has already been selected.`)}let f=n.namesPrefix??"",a=n.namesSep??"_",m=$e(l.map(c=>e[c]),r),u=$e(i.map(c=>e[c]),r),p=u.firsts.map((c,b)=>b);n.namesSort===!0&&p.sort((c,b)=>{for(let A of i){let R=ue(e[A][u.firsts[c]],e[A][u.firsts[b]]);if(R!==0)return R}return 0});let h=u.firsts.map(c=>f+i.map(b=>_n(e[b][c])).join(a)),N=u.firsts.length,E=Array.from({length:m.firsts.length*N},()=>[]);for(let c=0;c<r;c++)E[m.codes[c]*N+u.codes[c]].push(c);let O=c=>typeof c=="function",g=c=>typeof c!="object"||c===null;for(let c of s)if(ee(n.valuesFn,O,c)===void 0&&E.some(b=>b.length>1))throw new Error(`values from '${c}' are not uniquely identified; use valuesFn to summarise them`);let y=new Map;for(let c of s){let b=e[c],A=ee(n.valuesFn,O,c),R=new Array(E.length).fill(null),v=null;if(A===void 0)v=Me(c,b),E.forEach((M,k)=>{M.length>0&&(R[k]=b[M[0]])});else{let M=new Uint8Array(E.length),k=0,T=0;for(let j=0;j<r;j++){let C=m.codes[j]*N+u.codes[j];if(M[C]===1)continue;M[C]=1,T++;let U=A(E[C].map(ve=>b[ve]));if(R[C]=U,U==null)continue;let L=re(U);if(v===null||v==="logical"&&L==="double")v=L,k=T;else if(L!==v&&(v==="character"||L==="character"))throw new TypeError(`Can't combine \`x[[${k}]]\` <${v}> and \`x[[${T}]]\` <${L}>.`)}}let $=jn(ee(n.valuesFill,g,c)??null,v);y.set(c,{cells:R,type:v??($===null?null:re($)),fill:$})}let d=(c,b)=>{let A=e[c],{cells:R,type:v,fill:$}=y.get(c),M=m.firsts.map((k,T)=>{let j=T*N+b,C=E[j].length===0?$:R[j];return v==="double"&&typeof C=="boolean"?Number(C):C});return A instanceof Float64Array&&(v==="double"||v===null)?Float64Array.from(M,k=>k===null?NaN:k):M},w={};for(let c of l)F(w,c,J(e[c],m.firsts));let x=(c,b)=>s.length===1?h[b]:`${c}${a}${h[b]}`;if(t==="slowest")for(let c of p)for(let b of s)F(w,x(b,c),d(b,c));else for(let c of s)for(let b of p)F(w,x(c,b),d(c,b));return w}export{H as IQR,vn as aggregate,pe as completeCases,ke as cor,Re as cov,qe as cummax,ze as cummin,Ve as cumprod,Ue as cumsum,en as cut,Je as cv,Be as diff,dn as ecdf,nn as findInterval,on as fivenum,je as fromRows,Ze as geometricMean,hn as hist,We as kurtosis,sn as mad,Ie as mean,Ge as meanAD,_ as median,Fe as merge,Qe as modes,an as naOmit,Tn as pivotLonger,Sn as pivotWider,ge as pretty,Se as prod,W as quantile,S as range,Oe as rank,Xe as scale,D as sd,De as skewness,An as split,Te as subset,_e as sum,Ke as table,He as tabulate,En as tapply,Ce as toRows,Ye as unique,Pe as variance,Le as weightedMean};
@@ -19,8 +19,19 @@ export function darcsine1(x, a, b, log) {
19
19
  return d0(log);
20
20
  if (x === a || x === b)
21
21
  return Infinity;
22
- if (!log)
23
- return 1 / (Math.PI * Math.sqrt(x - a) * Math.sqrt(b - x)); // sqrt of each: the product can over- or underflow
22
+ // b - a overflows (both finite): the density of X/2 on (a/2, b/2), halved
23
+ if (!Number.isFinite(b - a)) {
24
+ const h = darcsine1(x * 0.5, a * 0.5, b * 0.5, log);
25
+ return log ? h - Math.LN2 : h * 0.5;
26
+ }
27
+ if (!log) {
28
+ // sqrt of each: the product (x - a)(b - x) can over- or underflow. Where pi sqrt(x - a) sqrt(b - x) overflows, divide
29
+ // in two steps (the density at the middle of (0, 1.7e308) was 0, not 3.7e-309)
30
+ const sa = Math.sqrt(x - a);
31
+ const sb = Math.sqrt(b - x);
32
+ const den = Math.PI * sa * sb;
33
+ return Number.isFinite(den) ? 1 / den : 1 / (Math.PI * sa) / sb;
34
+ }
24
35
  // -log(pi) - (log(x - a) + log(b - x)) / 2 in double-double from the exact differences (the log of a density near 1
25
36
  // would turn its rounding into a large relative error)
26
37
  const l = ddAdd(ddLog(twoSum(x, -a)), ddLog(twoSum(b, -x)));
@@ -40,6 +51,9 @@ export function parcsine1(q, a, b, lowerTail, logP) {
40
51
  return dt0(lowerTail, logP);
41
52
  if (q >= b)
42
53
  return dt1(lowerTail, logP);
54
+ // b - a overflows (both finite): the same probability on the halved scale (parcsine(0, -1e308, 1e308) was 0, not 1/2)
55
+ if (!Number.isFinite(b - a))
56
+ return parcsine1(q * 0.5, a * 0.5, b * 0.5, lowerTail, logP);
43
57
  const w = b - a;
44
58
  const nearA = q - a <= b - q;
45
59
  // distance to the nearer end, and the tail on that side
@@ -65,6 +79,9 @@ export function qarcsine1(p, a, b, lowerTail, logP) {
65
79
  const bd = quantileBoundaries(p, a, b, lowerTail, logP);
66
80
  if (bd !== undefined)
67
81
  return bd;
82
+ // b - a overflows (both finite): twice the quantile on the halved scale (qarcsine(0.5, -1e308, 1e308) was Inf, not 0)
83
+ if (!Number.isFinite(b - a))
84
+ return 2 * qarcsine1(p, a * 0.5, b * 0.5, lowerTail, logP);
68
85
  // Where the lower or upper probability is below e^-40, the distance to that end is w sin^2(pi p / 2) = w (pi p / 2)^2
69
86
  // (1 - O(p^2)), from logs (sin^2 underflowed: qarcsine(1.7e-208, 0, 2.6e187) was 0, not 1.9e-228). The log of a
70
87
  // tiny probability in double-double from its linear value (log p rounded loses eps |log p| relative); 1 - p is exact
@@ -30,13 +30,26 @@ function dbetaCore(x, a, b, log) {
30
30
  const l = dbetaDirectLog(xd, xcd, a, b);
31
31
  return log ? l : Math.exp(l);
32
32
  }
33
- const { e } = dbinomExponent(a, b, xd, xcd);
33
+ // a + b overflows (both shapes near the largest double): the deviances are homogeneous, bd0(cx, cM) = c bd0(x, M), so
34
+ // E is twice that of the halved shapes (the stirlerr terms, about 1/(12 a), are below 1e-308 there). The density was 0
35
+ // where it is 1.1e154: dbeta(0.5, 1e308, 1e308)
36
+ const sumOverflows = !Number.isFinite(a + b);
37
+ let e;
38
+ if (sumOverflows) {
39
+ const h = dbinomExponent(a * 0.5, b * 0.5, xd, xcd).e;
40
+ e = h[0] === Infinity ? h : [2 * h[0], 2 * h[1]];
41
+ }
42
+ else
43
+ e = dbinomExponent(a, b, xd, xcd).e;
34
44
  // (a deviance beyond the doubles, from a shape near the largest double: the density is 0, where the double-double sums
35
45
  // below were NaN: dbeta(0.998, 55.1, 6.3e307))
36
46
  if (e[0] === Infinity)
37
47
  return d0(log);
38
48
  // With m = ab/(a+b), log(denom)/2 = log(2 pi m)/2 and log(ab/(a+b)) - log(denom)/2 = log(m/(2 pi))/2
39
- const m = (a * b) / (a + b);
49
+ const lo = Math.min(a, b);
50
+ const hi = Math.max(a, b);
51
+ const m = sumOverflows ? lo / (1 + lo / hi) : (a * b) / (a + b);
52
+ const logSum = sumOverflows ? Math.log(hi) + Math.log1p(lo / hi) : Math.log(a + b);
40
53
  if (!log && e[0] < 700 && x > 1e-290 && xcd[0] > 1e-290) {
41
54
  // f = exp(-E) sqrt(m/(2 pi)) / (x (1 - x)) on the linear scale: no logarithms are needed, and the factors after
42
55
  // exp(-E) cost a few roundings whatever the size of log x (in the log form, log x near -700 alone would carry
@@ -52,7 +65,7 @@ function dbetaCore(x, a, b, log) {
52
65
  const lxx = x > 1e-290 && xcd[0] > 1e-290 ? ddLog(ddMul(xd, xcd)) : ddAdd(ddLog(xd), ddLog(xcd));
53
66
  const lc = m > 1e-290 && m < 1e290
54
67
  ? 0.5 * Math.log(m / (2 * Math.PI))
55
- : 0.5 * (Math.log(a) + Math.log(b) - Math.log(a + b) - Math.log(2 * Math.PI));
68
+ : 0.5 * (Math.log(a) + Math.log(b) - logSum - Math.log(2 * Math.PI));
56
69
  const t = ddAdd(ddNeg(ddAdd(e, lxx)), [lc, 0]);
57
70
  return log ? t[0] + t[1] : Math.exp(t[0]) * (1 + t[1]);
58
71
  }
@@ -129,7 +142,11 @@ export function pbeta1(q, a, b, lowerTail, logP) {
129
142
  return NaN;
130
143
  if (q >= 1)
131
144
  return dt1(lowerTail, logP);
132
- // Point masses when a parameter is 0 or infinite (R checks this after q >= 1 and before q <= 0)
145
+ // Nothing lies left of the support, point masses at 0 included (R checks the point masses before q <= 0, so that
146
+ // pbeta(-1, 0, 2) was 1 and pbeta(-1, 0, 0) 0.5); at q = 0 the masses at 0 count
147
+ if (q < 0)
148
+ return dt0(lowerTail, logP);
149
+ // Point masses when a parameter is 0 or infinite
133
150
  if (a === 0 || b === 0 || !Number.isFinite(a) || !Number.isFinite(b)) {
134
151
  if (a === 0 && b === 0)
135
152
  return logP ? -Math.LN2 : 0.5; // 1/2 each at 0 and 1
@@ -276,6 +293,9 @@ export function qbeta1(p, a, b, lowerTail, logP) {
276
293
  // Decide whether the answer lies left or right of 1/2 by comparing with the distribution function at x = 1/2
277
294
  // (for skewed distributions the answer can be near 0 even when the lower probability exceeds 1/2)
278
295
  const atHalf = betaInc(a, b, 0.5, 0.5, lower, true);
296
+ // (a NaN would send the search to the right half and return a wrong value)
297
+ if (Number.isNaN(atHalf))
298
+ return NaN;
279
299
  const leftHalf = lower ? logTarget <= atHalf : logTarget >= atHalf;
280
300
  if (leftHalf)
281
301
  return solveLeftHalf(a, b, lower, logTarget, linearTarget);
@@ -9,8 +9,10 @@ import { discreteQuantile } from "../internal/discrete.js";
9
9
  import { betaInc } from "../special/incbet.js";
10
10
  import { dbinomRawDD } from "../special/loader.js";
11
11
  import { twoSum } from "../special/dd.js";
12
+ import { logAddExp, logSubExp } from "../internal/ddexp.js";
12
13
  import { qnorm } from "./normal.js";
13
14
  import { nonInteger } from "./poisson.js";
15
+ import { countAtMost, roundHalfEven } from "../internal/integer.js";
14
16
  function badParams(size, prob) {
15
17
  return nonInteger(size) || size < 0 || !Number.isFinite(size) || prob < 0 || prob > 1;
16
18
  }
@@ -31,12 +33,37 @@ export function dbinom1(x, size, prob, log) {
31
33
  return d0(log);
32
34
  const pd = prob <= 0.5 ? [prob, 0] : twoSum(1, -(1 - prob));
33
35
  const qd = prob <= 0.5 ? twoSum(1, -prob) : [1 - prob, 0];
34
- return dbinomRawDD(xr, n - xr, pd, qd, log);
36
+ return dbinomRawDD(xr, n - xr, pd, qd, log, n);
35
37
  }
36
38
  /** P[X <= x] (lower) / P[X > x] (!lower). x an integer, 0 <= x < n */
37
39
  function pbinomRaw(x, n, prob, lower, log) {
38
40
  // P[X <= x] = 1 - I_p(x + 1, n - x)
39
- return betaInc(x + 1, n - x, prob, 1 - prob, !lower, log);
41
+ if (x + 1 - x === 1)
42
+ return betaInc(x + 1, n - x, prob, 1 - prob, !lower, log);
43
+ // Beyond 2^53, x + 1 rounds (to x, or up to x + 2) (pbinom(1e16, 2e16, 0.5) was 0.5, the symmetric I_p(x, x); R too). Without x + 1:
44
+ // I_p(x + 1, n - x) = I_p(x, n - x) - (n - x)/n dbinom(x; n, p). With n - x itself rounded, no parameters are right
45
+ const [b, err] = twoSum(n, -x);
46
+ if (err !== 0)
47
+ return NaN;
48
+ let v;
49
+ let term;
50
+ if (!log) {
51
+ const t = betaInc(x, b, prob, 1 - prob, !lower, false);
52
+ term = (b / n) * dbinom1(x, n, prob, false);
53
+ v = lower ? t + term : t - term;
54
+ }
55
+ else {
56
+ const lt = betaInc(x, b, prob, 1 - prob, !lower, true);
57
+ term = Math.log(b / n) + dbinom1(x, n, prob, true);
58
+ v = lower ? logAddExp(lt, term) : logSubExp(lt, term);
59
+ }
60
+ if (Number.isNaN(term))
61
+ return NaN;
62
+ // The upper tail as a difference: where the term is not resolved against it (deep tails, where both logs round to the
63
+ // same value), one unit of x is below the resolution of the result, and the rounded x + 1 serves (round 55)
64
+ if (lower || (log ? Number.isFinite(v) : v > 0))
65
+ return v;
66
+ return betaInc(x + 1, b, prob, 1 - prob, !lower, log);
40
67
  }
41
68
  export function pbinom1(q, size, prob, lowerTail, logP) {
42
69
  if (Number.isNaN(q) || Number.isNaN(size) || Number.isNaN(prob))
@@ -46,7 +73,7 @@ export function pbinom1(q, size, prob, lowerTail, logP) {
46
73
  const n = Math.round(size);
47
74
  if (q < 0)
48
75
  return dt0(lowerTail, logP);
49
- const x = Math.floor(q + 1e-7);
76
+ const x = countAtMost(q);
50
77
  if (n <= x)
51
78
  return dt1(lowerTail, logP);
52
79
  if (prob === 0)
@@ -58,15 +85,16 @@ export function pbinom1(q, size, prob, lowerTail, logP) {
58
85
  export function qbinom1(p, size, prob, lowerTail, logP) {
59
86
  if (Number.isNaN(p) || Number.isNaN(size) || Number.isNaN(prob))
60
87
  return NaN;
61
- if (!Number.isFinite(size) || !Number.isFinite(prob) || prob < 0 || prob > 1 || size < 0)
88
+ if (!Number.isFinite(size) || !Number.isFinite(prob))
62
89
  return NaN;
63
- // R returns the endpoints (p = 0, 1) first even for non-integer size. The upper end is size rounded half to even
64
- const b = quantileBoundaries(p, 0, roundHalfEven(size), lowerTail, logP);
90
+ // As R (R_forceint), a non-integer size is rounded half to even (10.5 is 10, -0.1 is -0), as in qhyper, qsignrank and
91
+ // qwilcox; dbinom and pbinom give NaN for it, as R
92
+ const n = roundHalfEven(size);
93
+ if (prob < 0 || prob > 1 || n < 0)
94
+ return NaN;
95
+ const b = quantileBoundaries(p, 0, n, lowerTail, logP);
65
96
  if (b !== undefined)
66
97
  return b;
67
- if (badParams(size, prob))
68
- return NaN;
69
- const n = Math.round(size);
70
98
  if (prob === 0 || n === 0)
71
99
  return 0;
72
100
  if (prob === 1)
@@ -150,8 +178,3 @@ export function qbinom(p, size, prob, options = {}) {
150
178
  const { lowerTail = true, logP = false } = options;
151
179
  return vectorize(p, (v) => qbinom1(v, size, prob, lowerTail, logP));
152
180
  }
153
- /** Round half to even (0.5 goes to the nearest even number; same as R's nearbyint) */
154
- function roundHalfEven(x) {
155
- const r = Math.round(x);
156
- return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r;
157
- }
@@ -41,8 +41,12 @@ const upperPhi = (x) => pnorm(x, { lowerTail: false });
41
41
  function upperOrthant(h, k, r) {
42
42
  if (r === 1)
43
43
  return upperPhi(Math.max(h, k));
44
- if (r === -1)
45
- return Math.max(0, upperPhi(h) - pnorm(-k));
44
+ // r = -1: Y = -X, so P(h < X < -k) (this was Φ(k) − Φ(h); issue #23), from the tails on the side of h for accuracy
45
+ if (r === -1) {
46
+ if (h >= -k)
47
+ return 0;
48
+ return h >= 0 ? upperPhi(h) - upperPhi(-k) : pnorm(-k) - pnorm(h);
49
+ }
46
50
  const { x, w } = RULES[Math.abs(r) < 0.3 ? 0 : Math.abs(r) < 0.75 ? 1 : 2];
47
51
  const hk = h * k;
48
52
  if (Math.abs(r) < 0.925) {
@@ -124,6 +128,11 @@ export function pbvnorm(lower, upper, rho) {
124
128
  let [b1, b2] = upper;
125
129
  if ([a1, a2, b1, b2].some(Number.isNaN))
126
130
  return NaN;
131
+ // A bound beyond ±40 is taken as infinite (before the reflection below, which then decides as for infinite bounds):
132
+ // Φ(-40) is 3.7e-350, far below half the least subnormal, so the probability moves by less than the doubles resolve.
133
+ // Huge finite bounds overflowed h k and h^2 (Inf - Inf, 0 * Inf) and made the rectangle NaN (pbvnorm([-1e200, -1e200],
134
+ // [Inf, Inf], 0.5) for 1; issue #119)
135
+ [a1, a2, b1, b2] = [a1, a2, b1, b2].map((v) => (v > 40 ? Infinity : v < -40 ? -Infinity : v));
127
136
  if (!(a1 < b1 && a2 < b2))
128
137
  return 0;
129
138
  // reflect a rectangle in the lower half into the upper half
@@ -60,7 +60,7 @@ export function dcauchy1(x, location, scale, log) {
60
60
  const y = scale / ah / 2;
61
61
  if (log)
62
62
  return -(LOG_PI + Math.log(scale)) - 2 * (Math.log(ah) + Math.LN2 - Math.log(scale)) - Math.log1p(y * y);
63
- return (y / (Math.PI * scale)) * (y / (1 + y * y));
63
+ return overPiScale(y, scale) * (y / (1 + y * y));
64
64
  }
65
65
  const az = Math.abs(z);
66
66
  if (scale < MIN_NORMAL)
@@ -68,13 +68,19 @@ export function dcauchy1(x, location, scale, log) {
68
68
  if (az <= 1) {
69
69
  if (log)
70
70
  return -(LOG_PI + Math.log(scale)) - Math.log1p(z * z);
71
- return 1 / (Math.PI * scale * (1 + z * z));
71
+ // (π scale overflows above 5.7e307: then 1/π first; the density was 0, R's too; issue #25)
72
+ return Number.isFinite(Math.PI * scale) ? 1 / (Math.PI * scale * (1 + z * z)) : 1 / Math.PI / scale / (1 + z * z);
72
73
  }
73
74
  // With y = 1/z, f = y^2 / (π scale (1 + y^2))
74
75
  const y = 1 / az;
75
76
  if (log)
76
77
  return -(LOG_PI + Math.log(scale)) - 2 * Math.log(az) - Math.log1p(y * y);
77
- return (y / (Math.PI * scale)) * (y / (1 + y * y));
78
+ return overPiScale(y, scale) * (y / (1 + y * y));
79
+ }
80
+ /** y / (π scale), with 1/π first where π scale overflows (above 5.7e307 the density was 0, R's too; issue #25) */
81
+ function overPiScale(y, scale) {
82
+ const ps = Math.PI * scale;
83
+ return Number.isFinite(ps) ? y / ps : y / Math.PI / scale;
78
84
  }
79
85
  /**
80
86
  * P[X <= q] (lower) / P[X > q] (!lower). For |z| > 1 the smaller tail atan(1/|z|)/π is computed without forming z,
@@ -151,7 +157,9 @@ export function qcauchy1(p, location, scale, lowerTail, logP) {
151
157
  return NaN;
152
158
  if (logP ? p > 0 : p < 0 || p > 1)
153
159
  return NaN;
154
- if (!(scale > 0) || !Number.isFinite(scale))
160
+ // scale = Inf gives the limits (-Inf, location, Inf below, at and above the median), as dcauchy and pcauchy (0 and
161
+ // 1/2) and qnorm and qlogis do (R: NaN)
162
+ if (!(scale > 0))
155
163
  return scale === 0 ? location : NaN;
156
164
  // Standard quantile T for the probability p on that side (x = location + scale T for the lower tail)
157
165
  let t;
@@ -26,7 +26,9 @@ export function dchisq(x, df, options = {}) {
26
26
  const { log = false, ncp } = options;
27
27
  if (ncp !== undefined)
28
28
  return vectorize(x, (v) => dnchisq1(v, df, ncp, log));
29
- return vectorize(x, (v) => dgamma1(v, df / 2, 2, log));
29
+ // (df < 0 is invalid: df / 2 of -5e-324 rounded to -0, the point mass at 0, as in R; issue #26)
30
+ const half = df < 0 ? NaN : df / 2;
31
+ return vectorize(x, (v) => dgamma1(v, half, 2, log));
30
32
  }
31
33
  /**
32
34
  * Distribution function of the chi-squared distribution. Equivalent to R's `pchisq(q, df, ncp = 0, lower.tail = TRUE, log.p = FALSE)`.
@@ -50,7 +52,8 @@ export function pchisq(q, df, options = {}) {
50
52
  const { lowerTail = true, logP = false, ncp } = options;
51
53
  if (ncp !== undefined)
52
54
  return vectorize(q, (v) => pnchisq1(v, df, ncp, lowerTail, logP));
53
- return vectorize(q, (v) => pgamma1(v, df / 2, 2, lowerTail, logP));
55
+ const half = df < 0 ? NaN : df / 2;
56
+ return vectorize(q, (v) => pgamma1(v, half, 2, lowerTail, logP));
54
57
  }
55
58
  /**
56
59
  * Quantile function of the chi-squared distribution. Equivalent to R's `qchisq(p, df, ncp = 0, lower.tail = TRUE, log.p = FALSE)`.
@@ -74,5 +77,6 @@ export function qchisq(p, df, options = {}) {
74
77
  const { lowerTail = true, logP = false, ncp } = options;
75
78
  if (ncp !== undefined)
76
79
  return vectorize(p, (v) => qnchisq1(v, df, ncp, lowerTail, logP));
77
- return vectorize(p, (v) => qgamma1(v, df / 2, 2, lowerTail, logP));
80
+ const half = df < 0 ? NaN : df / 2;
81
+ return vectorize(p, (v) => qgamma1(v, half, 2, lowerTail, logP));
78
82
  }
@@ -50,6 +50,11 @@ export function pexp1(q, rate, lowerTail, logP) {
50
50
  return NaN;
51
51
  if (t[0] === Infinity)
52
52
  return dt1(lowerTail, logP);
53
+ // log(1 - exp(-t)) for t = rate q below the normal range: log rate + log q + log((1 - e^-t)/t), the last -t/2 to the
54
+ // double. The rounded subnormal product had lost its digits (pexp(1e-20, { rate: 1e-300, logP: true }) was
55
+ // -736.8272408909739 for log(1e-320) = -736.8272297580946, as R; issue #27)
56
+ if (lowerTail && logP && t[0] < 2 ** -1022 && t[0] > 0)
57
+ return Math.log(rate) + Math.log(q) + Math.log1p(-t[0] / 2);
53
58
  return expTail(t, lowerTail, logP);
54
59
  }
55
60
  export function qexp1(p, rate, lowerTail, logP) {
@@ -2,8 +2,8 @@
2
2
  //
3
3
  // The density uses the relation to the binomial probability. With p = m x/(n + m x) and q = n/(n + m x),
4
4
  // m >= 2: f(x) = m q / 2 * dbinom((m-2)/2; (m+n-2)/2, p)
5
- // m < 2: f(x) = m/(n + m x) * m n / (2 (m + n) p) * dbinom(m/2; (m+n)/2, p)
6
- // (both derived by rewriting the F density in terms of Gamma functions).
5
+ // (derived by rewriting the F density in terms of Gamma functions); m < 2 (or n < 2) is computed from the log of the
6
+ // density with the small-shape prefactor (fLogDensity).
7
7
  // The distribution function is P[F <= x] = I_p(m/2, n/2); quantiles use Newton's method in u = log x.
8
8
  import { vectorize } from "../internal/vectorize.js";
9
9
  import { d0, dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
@@ -16,7 +16,8 @@ import { ddAdd, ddDiv, ddLog, ddMul, ddNeg, ddSub, twoProd, twoSum } from "../sp
16
16
  import { dgamma1, pgamma1, qgamma1 } from "./gamma.js";
17
17
  import { dnf1, pnf1, qnf1 } from "./nbeta.js";
18
18
  import { betaQuantileGuess } from "./beta.js";
19
- const LOG_DBL_MIN = Math.log(2.2250738585072014e-308);
19
+ const DBL_MIN = 2.2250738585072014e-308;
20
+ const LOG_DBL_MIN = Math.log(DBL_MIN);
20
21
  /**
21
22
  * Log density in double-double from log p and log q (p = m x/(n + m x), q = 1 - p = n/(n + m x)), with a = m/2, b = n/2:
22
23
  * f(x) = (m/n) p^(a-1) q^(b+1) / B(a, b) (the beta density of p times dp/dx = (m/n) q^2)
@@ -47,8 +48,17 @@ function fRatios(x, m, n) {
47
48
  // (pf(1e301, 1.4e-312, 6.72, { lowerTail: false }) was 1, 1.77e-311 expected; qf there did not return)
48
49
  const S = 2 ** 600;
49
50
  let mx = x > 1e290 ? twoProd(m * S, x / S) : m > 1e290 ? twoProd(m / S, x * S) : twoProd(m, x);
50
- if (!(Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290))
51
- return undefined;
51
+ if (!(Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290)) {
52
+ // m x and n both divided by 2^600 (exactly): a huge m x is not always far above n, and the callers' p ≈ 1 gave
53
+ // pf(1e150, 1e150, 1e308) the wrong tail (lower -Inf for 0 in logs; issue #116). Where m x is still huge or n falls
54
+ // below 1e-290 there, m x is far above n and the callers' p ≈ 1, q ≈ n/(m x) holds
55
+ const mxS = twoProd(Math.max(m, x) / S, Math.min(m, x));
56
+ const nS = n / S;
57
+ if (!(Number.isFinite(mxS[0]) && Number.isFinite(mxS[1]) && Math.abs(mxS[0]) < 1e290) || !(nS >= 1e-290))
58
+ return undefined;
59
+ const dS = ddAdd(mxS, [nS, 0]);
60
+ return [ddDiv(mxS, dS), ddDiv([nS, 0], dS)];
61
+ }
52
62
  let nn = n;
53
63
  if (x > 0 && mx[0] < 1e-290 && n < 1e127) {
54
64
  mx = m < x ? twoProd(m * S, x) : twoProd(m, x * S);
@@ -83,15 +93,11 @@ function fDensity(x, m, n, log) {
83
93
  // below underflowed (df(6.6e-112, 3.2e-173, 1868) was -Infinity on the log scale, NaN at x = 4.6e-157)
84
94
  if (Math.min(m, n) / 2 < SMALL_SHAPE)
85
95
  return fromLog(fLogDensity(m, n, ddLog(pd), ddLog(qd)), log);
86
- const p = pd[0];
96
+ // (m >= 2 here: SMALL_SHAPE is 1, so df1 < 2 took the branch above; R's form for df1 < 2, whose 2 (m + n) overflowed
97
+ // for df2 near 1e308, was never reached and is gone; issue #32)
87
98
  const q = qd[0];
88
- if (m >= 2) {
89
- const c = (m * q) / 2;
90
- const v = dbinomRawDD((m - 2) / 2, n / 2, pd, qd, log);
91
- return log ? Math.log(c) + v : c * v;
92
- }
93
- const c = ((m / (n + m * x)) * m * n) / (2 * (m + n) * p);
94
- const v = dbinomRawDD(m / 2, n / 2, pd, qd, log);
99
+ const c = (m * q) / 2;
100
+ const v = dbinomRawDD((m - 2) / 2, n / 2, pd, qd, log);
95
101
  return log ? Math.log(c) + v : c * v;
96
102
  }
97
103
  export function dfDensity1(x, m, n, log) {
@@ -110,16 +116,25 @@ export function dfDensity1(x, m, n, log) {
110
116
  }
111
117
  if (!Number.isFinite(m) && !Number.isFinite(n))
112
118
  return x === 1 ? Infinity : d0(log);
119
+ // The density tends to 0 as x -> Inf for every df1 and df2 (x^(-df2/2 - 1)). R gives NaN for df1 < 2 and for
120
+ // df1 = Inf with df2 < 2 (Inf / Inf in its forms; #493)
121
+ if (x === Infinity)
122
+ return d0(log);
113
123
  if (!Number.isFinite(n))
114
124
  return dgamma1(x, m / 2, 2 / m, log); // χ²_m / m
115
125
  if (!Number.isFinite(m)) {
116
126
  // n / χ²_n: 1/x follows a gamma distribution with shape n/2, scale 2/n
117
- // At tiny x this is 0 / 0 = NaN (x^2 underflows), as R gives (df(1e-300, Inf, 5) is NaN); the log is finite
118
127
  const dens = dgamma1(1 / x, n / 2, 2 / n, log);
119
- return log ? dens - 2 * Math.log(x) : dens / (x * x);
128
+ if (log)
129
+ return dens - 2 * Math.log(x);
130
+ // Where the gamma density or x^2 leaves the normal range, the quotient is 0 / 0 = NaN (df(1e-300, Inf, 5); R the
131
+ // same), or 0 where the density underflows or x^2 overflows (df(1e160, Inf, 1) is 3.99e-241; R 0): from the log
132
+ // (#493). Elsewhere the quotient and its bits are kept
133
+ const x2 = x * x;
134
+ if (dens >= DBL_MIN && dens < Infinity && x2 >= DBL_MIN && x2 < Infinity)
135
+ return dens / x2;
136
+ return Math.exp(dgamma1(1 / x, n / 2, 2 / n, true) - 2 * Math.log(x));
120
137
  }
121
- if (!Number.isFinite(x))
122
- return m < 2 ? NaN : d0(log); // R gives NaN at x = Inf when df1 < 2
123
138
  return fDensity(x, m, n, log);
124
139
  }
125
140
  /**
@@ -22,7 +22,8 @@ import { qnorm } from "./normal.js";
22
22
  export function gammaScale(params) {
23
23
  const { rate, scale } = params;
24
24
  if (rate !== undefined && scale !== undefined) {
25
- if (Math.abs(rate * scale - 1) >= 1e-15) {
25
+ // (as R: a product that is NaN, from rate = NaN or Inf * 0, is an error too; it passed with >=)
26
+ if (!(Math.abs(rate * scale - 1) < 1e-15)) {
26
27
  throw new RangeError("rate and scale can both be given only when scale = 1 / rate");
27
28
  }
28
29
  return scale;
@@ -165,8 +166,22 @@ export function pgamma1(q, shape, scale, lowerTail, logP) {
165
166
  }
166
167
  if (x <= 0)
167
168
  return dt0(lowerTail, logP);
169
+ if (x === Infinity && !lowerTail && logP && scale < Infinity && overflowLogUpperFinite(q, shape, scale))
170
+ return NaN;
168
171
  return gammaInc(shape, x, lowerTail, logP);
169
172
  }
173
+ /**
174
+ * Whether log Q(shape, q / scale) may be finite although q / scale overflows (#368). The other tails are right there
175
+ * (P = 1, Q = 0 and log P = 0 to double precision: q / scale exceeds even the largest shape by far more than its
176
+ * standard deviation), and so is log Q = -Inf where its leading term shape (r - 1 - log r), r = q / (shape scale),
177
+ * overflows. Where that term is finite (a shape of about 1e290 and above) log Q is finite, but gammaInc sees only
178
+ * x = Inf and returns -Inf: such values are NaN, not computed (user decision, 2026-11-03)
179
+ */
180
+ function overflowLogUpperFinite(q, shape, scale) {
181
+ const ps = shape * scale;
182
+ const r = ps >= MIN_NORMAL ? q / ps : Math.exp(Math.log(q) - Math.log(scale) - Math.log(shape));
183
+ return shape * (r - 1 - Math.log(r)) < Infinity;
184
+ }
170
185
  /**
171
186
  * log of the standardized gamma quantile when it is below the smallest normal double (else undefined): there
172
187
  * P(shape, x) = x^shape / Gamma(shape + 1) to double precision, so log x = (log P + lgamma(shape + 1)) / shape.
@@ -230,16 +245,25 @@ export function qgammaStd(p, shape, lowerTail, logP, scale = 1) {
230
245
  hi: Infinity,
231
246
  positive: true,
232
247
  });
248
+ // The standardized quantile beyond the largest double (#368): the search stops at Number.MAX_VALUE, and x * scale
249
+ // was MAX_VALUE times scale (qgamma(-1e308, 1e308, scale 1e-308, upper, log) 1.797, the true value about 3.146). With
250
+ // scale >= 1 the quantile is Inf; below 1 it may be finite but is not computed here: NaN (user decision, 2026-11-03)
251
+ if (x >= 2 ** 1000) {
252
+ const atMax = gammaInc(shape, Number.MAX_VALUE, lower, true);
253
+ if (lower ? atMax < logTarget : atMax > logTarget)
254
+ return scale >= 1 ? Infinity : NaN;
255
+ }
233
256
  return x * scale;
234
257
  }
235
258
  export function qgamma1(p, shape, scale, lowerTail, logP) {
236
259
  if (Number.isNaN(p) || Number.isNaN(shape) || Number.isNaN(scale))
237
260
  return NaN;
261
+ // parameters that define no distribution before the ends, as dgamma and pgamma (R gives 0 and Inf at p = 0 and 1)
262
+ if (shape < 0 || scale <= 0)
263
+ return NaN;
238
264
  const b = quantileBoundaries(p, 0, Infinity, lowerTail, logP);
239
265
  if (b !== undefined)
240
266
  return b;
241
- if (shape < 0 || scale <= 0)
242
- return NaN;
243
267
  if (shape === 0)
244
268
  return 0;
245
269
  // Shape Inf: all the mass at +Inf, so every probability strictly between 0 and 1 maps to Inf