@numero-uno-jpn/rstats 0.11.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +100 -0
- package/README.ja.md +49 -19
- package/README.md +45 -15
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/dist/chunks/chunk-22SXZNR6.js +2 -0
- package/dist/chunks/chunk-2IAT6MT2.js +2 -0
- package/dist/chunks/chunk-3AKA4KEL.js +3 -0
- package/dist/chunks/{chunk-2X7JYQBI.js → chunk-4AQNVF3Z.js} +2 -2
- package/dist/chunks/chunk-4GNJEYXR.js +2 -0
- package/dist/chunks/chunk-AGRKZXLG.js +2 -0
- package/dist/chunks/{chunk-GG4BJMJW.js → chunk-BJHBYEEU.js} +1 -1
- package/dist/chunks/chunk-BSOUJPDF.js +2 -0
- package/dist/chunks/{chunk-WQPFDDIY.js → chunk-CQNVEA22.js} +2 -2
- package/dist/chunks/{chunk-HITD7CX6.js → chunk-F44XUHWI.js} +1 -1
- package/dist/chunks/chunk-JGFUZKLJ.js +2 -0
- package/dist/chunks/{chunk-ETOEZTGL.js → chunk-MEMYFTYS.js} +1 -1
- package/dist/chunks/{chunk-ZRJQD7VS.js → chunk-N3FV6H3C.js} +2 -2
- package/dist/chunks/chunk-NRV3BH7I.js +2 -0
- package/dist/chunks/chunk-RTWLZPPG.js +2 -0
- package/dist/chunks/chunk-SLSDFIW2.js +2 -0
- package/dist/chunks/chunk-SVWU5T7C.js +2 -0
- package/dist/chunks/chunk-VG67L3JA.js +3 -0
- package/dist/chunks/chunk-VWGJYRE6.js +2 -0
- package/dist/data/grouping.d.ts +6 -3
- package/dist/data/grouping.js +30 -26
- package/dist/descriptive/basic.js +57 -49
- package/dist/descriptive/cov.js +7 -2
- package/dist/descriptive/factanal.d.ts +16 -0
- package/dist/descriptive/factanal.js +26 -0
- package/dist/descriptive/hist.d.ts +8 -2
- package/dist/descriptive/hist.js +10 -2
- package/dist/descriptive/quantile.d.ts +8 -3
- package/dist/descriptive/quantile.js +10 -6
- package/dist/descriptive/table.d.ts +7 -5
- package/dist/descriptive/table.js +39 -22
- package/dist/descriptive.js +2 -2
- package/dist/distributions/beta.js +17 -0
- package/dist/distributions/binomial.js +3 -0
- package/dist/distributions/gamma.js +7 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/mixed.d.ts +1 -0
- package/dist/entries/mixed.js +2 -0
- package/dist/entries/tests.d.ts +1 -1
- package/dist/htest/agreement.js +7 -2
- package/dist/htest/groups.js +7 -3
- package/dist/htest/mcnemarTest.js +6 -2
- package/dist/htest/pairwise.js +6 -3
- package/dist/htest/polycor.js +5 -3
- package/dist/htest/tTest.d.ts +3 -2
- package/dist/htest/tTest.js +6 -3
- package/dist/htest/testFormula.js +6 -3
- package/dist/htest/trendTests.js +10 -5
- package/dist/internal/levels.d.ts +11 -0
- package/dist/internal/levels.js +48 -0
- package/dist/internal/summary.d.ts +19 -1
- package/dist/internal/summary.js +69 -8
- package/dist/linalg/balance.d.ts +21 -0
- package/dist/linalg/balance.js +191 -0
- package/dist/linalg/eigen.d.ts +1 -1
- package/dist/linalg/eigen.js +8 -2
- package/dist/linalg/expm.d.ts +1 -11
- package/dist/linalg/expm.js +2 -158
- package/dist/linalg/kappa.d.ts +6 -2
- package/dist/linalg/kappa.js +16 -7
- package/dist/linalg/lu.d.ts +13 -2
- package/dist/linalg/lu.js +17 -3
- package/dist/linalg/qr.d.ts +4 -1
- package/dist/linalg/qr.js +2 -2
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +3 -0
- package/dist/models/aovEz.js +6 -4
- package/dist/models/aovStrata.d.ts +1 -1
- package/dist/models/aovStrata.js +5 -1
- package/dist/models/coxph.js +5 -2
- package/dist/models/formula.d.ts +26 -1
- package/dist/models/formula.js +125 -9
- package/dist/models/glm.d.ts +4 -1
- package/dist/models/glmFamily.d.ts +1 -1
- package/dist/models/glmFamily.js +24 -2
- package/dist/models/lm.d.ts +2 -2
- package/dist/models/lmer.d.ts +162 -0
- package/dist/models/lmer.js +457 -0
- package/dist/models/mauchly.js +2 -1
- package/dist/models/mixedDeviance.d.ts +44 -0
- package/dist/models/mixedDeviance.js +872 -0
- package/dist/models/mixedStructure.d.ts +82 -0
- package/dist/models/mixedStructure.js +309 -0
- package/dist/models/modelFrame.d.ts +12 -1
- package/dist/models/modelFrame.js +38 -22
- package/dist/models/modelMatrix.d.ts +15 -4
- package/dist/models/modelMatrix.js +18 -4
- package/dist/models/survival.js +5 -1
- package/dist/numerics/integrate.d.ts +1 -1
- package/dist/numerics/integrate.js +13 -3
- package/dist/numerics/interp.d.ts +1 -1
- package/dist/numerics/interp.js +3 -0
- package/dist/numerics.js +2 -2
- package/dist/rstats.js +14 -14
- package/dist/special/beta.js +10 -20
- package/dist/special.js +2 -2
- package/dist/tests.js +12 -12
- package/llms.txt +11 -3
- package/package.json +5 -1
- package/dist/chunks/chunk-36GVER3O.js +0 -2
- package/dist/chunks/chunk-3WUXRSM6.js +0 -2
- package/dist/chunks/chunk-6I6QKTFK.js +0 -2
- package/dist/chunks/chunk-FVPDVRJQ.js +0 -3
- package/dist/chunks/chunk-KK4GE65D.js +0 -2
- package/dist/chunks/chunk-LAUYSGV4.js +0 -3
- package/dist/chunks/chunk-M6GDXKKS.js +0 -2
- package/dist/chunks/chunk-PHHUHR7T.js +0 -2
- package/dist/chunks/chunk-X2AWQSVS.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! rStats.js 0.13.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
|
+
function M(c,r){return{nrow:c,ncol:r,data:new Float64Array(c*r)}}function E(c){return c.length>0&&typeof c[0]!="number"}function x(c){let r=c.length,o=r===0?0:c[0].length,t=M(r,o);for(let a=0;a<r;a++){let e=c[a];if(e.length!==o)throw new TypeError("all rows of the matrix must have the same length");for(let n=0;n<o;n++)t.data[a+n*r]=e[n]}return t}function A(c){if(E(c))return x(c);let r=c;return{nrow:r.length,ncol:1,data:Float64Array.from(r)}}function d(c){let r=[];for(let o=0;o<c.nrow;o++){let t=new Array(c.ncol);for(let a=0;a<c.ncol;a++)t[a]=c.data[o+a*c.nrow];r.push(t)}return r}function B(c){let r=M(c.ncol,c.nrow);for(let o=0;o<c.ncol;o++)for(let t=0;t<c.nrow;t++)r.data[o+t*c.ncol]=c.data[t+o*c.nrow];return r}function R(c,r="the matrix"){if(c.nrow!==c.ncol)throw new TypeError(`${r} must be square (got ${c.nrow} x ${c.ncol})`)}function _(c,r={}){let o=x(c);if(r.lapack){let{tau:n,pivot:l}=S(o),u=Array.from(n);return{qr:d(o),rank:Math.min(o.nrow,o.ncol),qraux:u,pivot:l.map(h=>h-1),useLapack:!0}}for(let n of o.data)if(!Number.isFinite(n))throw new RangeError("the matrix contains NaN or infinite values");let{qraux:t,pivot:a,rank:e}=O(o,r.tol??1e-7);return{qr:d(o),rank:e,qraux:Array.from(t),pivot:a.map(n=>n-1),useLapack:!1}}function g(c,r,o){let t=0;for(let e=0;e<o;e++)t=Math.max(t,Math.abs(c[r+e]));if(t===0||!Number.isFinite(t))return t;let a=0;for(let e=0;e<o;e++){let n=c[r+e]/t;a+=n*n}return t*Math.sqrt(a)}function O(c,r){let o=c.nrow,t=c.ncol,a=c.data,e=new Float64Array(t),n=new Float64Array(t),l=new Float64Array(t),u=Array.from({length:t},(i,p)=>p+1);for(let i=0;i<t;i++)e[i]=g(a,i*o,o),n[i]=e[i],l[i]=e[i]===0?1:e[i];let h=new Float64Array(o),f=Math.min(o,t),s=t;for(let i=0;i<f;i++){for(;i<s&&e[i]<l[i]*r;){h.set(a.subarray(i*o,(i+1)*o));let[w,q,N,v]=[e[i],n[i],l[i],u[i]];a.copyWithin(i*o,(i+1)*o,t*o),a.set(h,(t-1)*o),e.copyWithin(i,i+1),n.copyWithin(i,i+1),l.copyWithin(i,i+1),u.copyWithin(i,i+1),e[t-1]=w,n[t-1]=q,l[t-1]=N,u[t-1]=v,s--}if(i===o-1)break;let p=i*o,m=g(a,p+i,o-i);if(m!==0){a[p+i]!==0&&(m=Math.sign(a[p+i])*Math.abs(m));for(let w=i;w<o;w++)a[p+w]/=m;a[p+i]=1+a[p+i];for(let w=i+1;w<t;w++){let q=w*o,N=0;for(let k=i;k<o;k++)N-=a[p+k]*a[q+k];N/=a[p+i];for(let k=i;k<o;k++)a[q+k]+=N*a[p+k];if(e[w]===0)continue;let v=1-(Math.abs(a[q+i])/e[w])**2;v=Math.max(v,0);let Q=v;v=1+.05*v*(e[w]/n[w])**2,v!==1?e[w]*=Math.sqrt(Q):(e[w]=g(a,q+i+1,o-i-1),n[w]=e[w])}e[i]=a[p+i],a[p+i]=-m}}return{qraux:e,pivot:u,rank:Math.min(s,o)}}function S(c){let r=c.nrow,o=c.ncol,t=c.data,a=Math.min(r,o),e=new Float64Array(a),n=Array.from({length:o},(f,s)=>s+1),l=new Float64Array(o),u=new Float64Array(o);for(let f=0;f<o;f++)l[f]=g(t,f*r,r),u[f]=l[f];let h=Math.sqrt(2**-53);for(let f=0;f<a;f++){let s=f;for(let p=f+1;p<o;p++)Math.abs(l[p])>Math.abs(l[s])&&(s=p);if(s!==f){for(let p=0;p<r;p++){let m=t[p+s*r];t[p+s*r]=t[p+f*r],t[p+f*r]=m}[n[s],n[f]]=[n[f],n[s]],l[s]=l[f],u[s]=u[f]}let i=f*r;if(e[f]=T(t,i+f,r-f),f<o-1){let p=t[i+f];t[i+f]=1,z(t,i+f,r-f,e[f],c,f,f+1,o-f-1),t[i+f]=p}for(let p=f+1;p<o;p++){if(l[p]===0)continue;let m=1-(Math.abs(t[f+p*r])/l[p])**2;m=Math.max(m,0),m*(l[p]/u[p])**2<=h?f<r-1?(l[p]=g(t,p*r+f+1,r-f-1),u[p]=l[p]):(l[p]=0,u[p]=0):l[p]*=Math.sqrt(m)}}return{tau:e,pivot:n}}function T(c,r,o){if(o<=1)return 0;let t=g(c,r+1,o-1);if(t===0)return 0;let a=c[r],e=-Math.sign(a||1)*Math.hypot(a,t),n=2**-1022/2**-53,l=0;if(Math.abs(e)<n){let f=1/n;do{l++;for(let s=1;s<o;s++)c[r+s]*=f;e*=f,a*=f}while(Math.abs(e)<n&&l<20);t=g(c,r+1,o-1),e=-Math.sign(a||1)*Math.hypot(a,t)}let u=(e-a)/e,h=1/(a-e);for(let f=1;f<o;f++)c[r+f]*=h;for(let f=0;f<l;f++)e*=n;return c[r]=e,u}function z(c,r,o,t,a,e,n,l){if(t===0)return;let u=a.nrow,h=a.data;for(let f=n;f<n+l;f++){let s=e+f*u,i=0;for(let p=0;p<o;p++)i+=h[s+p]*c[r+p];i*=t;for(let p=0;p<o;p++)h[s+p]-=c[r+p]*i}}function j(c){return{a:x(c.qr),qraux:c.qraux,rank:c.rank,pivot:c.pivot.map(r=>r+1),lapack:c.useLapack}}function $(c,r){let o=A(r);if(o.nrow!==c.a.nrow)throw new TypeError(`qr and y must have the same number of rows (${c.a.nrow} and ${o.nrow})`);return o}function b(c,r){return E(c)?d(r):Array.from(r.data)}function y(c,r,o,t=c.rank){let{a,qraux:e}=c,n=a.nrow;if(c.lapack){let h=Math.min(n,a.ncol),f=o?F(0,h):F(0,h).reverse();for(let s of f){let i=a.data[s+s*n];a.data[s+s*n]=1,z(a.data,s+s*n,n-s,e[s],r,s,0,r.ncol),a.data[s+s*n]=i}return}let l=Math.min(t,n-1),u=o?F(0,l):F(0,l).reverse();for(let h of u){if(e[h]===0)continue;let f=h*n,s=a.data[f+h];a.data[f+h]=e[h];for(let i=0;i<r.ncol;i++){let p=i*n,m=0;for(let w=h;w<n;w++)m-=a.data[f+w]*r.data[p+w];m/=a.data[f+h];for(let w=h;w<n;w++)r.data[p+w]+=m*a.data[f+w]}a.data[f+h]=s}}function F(c,r){return Array.from({length:Math.max(0,r-c)},(o,t)=>c+t)}function H(c,r){let o=j(c),t=$(o,r);return y(o,t,!0),b(r,t)}function J(c,r){let o=j(c),t=$(o,r);return y(o,t,!1),b(r,t)}function W(c,r){let o=j(c),t=$(o,r),a=o.a.ncol,e=o.a.nrow,n=o.lapack?Math.min(e,a):o.rank;y(o,t,!0);for(let u=0;u<t.ncol;u++){let h=u*e;for(let f=n-1;f>=0;f--){let s=o.a.data[f+f*e];if(s===0)throw new Error("exact singularity in qrCoef");t.data[h+f]/=s;let i=-t.data[h+f];for(let p=0;p<f;p++)t.data[h+p]+=i*o.a.data[p+f*e]}}let l=M(a,t.ncol);l.data.fill(NaN);for(let u=0;u<t.ncol;u++)for(let h=0;h<n;h++)l.data[o.pivot[h]-1+u*a]=t.data[h+u*e];return b(r,l)}function L(c,r,o,t){let a=j(c);if(a.lapack)throw new TypeError("not supported for a QR decomposition computed with lapack: true");let e=t??a.rank;if(!Number.isInteger(e)||e<0||e>a.rank)throw new RangeError(`invalid k (got ${e})`);let n=$(a,r),l=a.a.nrow;if(e===0)return b(r,n);if(l===1)return o||n.data.fill(0),b(r,n);y(a,n,!0,e);for(let u=0;u<n.ncol;u++)o?n.data.fill(0,u*l+e,(u+1)*l):n.data.fill(0,u*l,u*l+e);return y(a,n,!1,e),b(r,n)}function K(c,r){return L(c,r,!1)}function U(c,r,o={}){return L(c,r,!0,o.k)}function V(c,r={}){let o=j(c),t=o.a.nrow,a=r.complete?t:Math.min(t,o.a.ncol),e=r.dvec??new Array(a).fill(1);if(e.length!==a)throw new RangeError(`dvec must have length ${a}`);let n=M(t,a);for(let l=0;l<a;l++)n.data[l+l*t]=e[l];return y(o,n,!1),d(n)}function Y(c,r={}){let o=x(c.qr),t=r.complete?o.nrow:Math.min(o.nrow,o.ncol),a=M(t,o.ncol);for(let e=0;e<o.ncol;e++)for(let n=0;n<=Math.min(e,t-1);n++)a.data[n+e*t]=o.data[n+e*o.nrow];return d(a)}function Z(c,r={}){let o=j(c),t=o.a.nrow,a=o.a.ncol,e=r.complete??!1,n=r.ncol??(e?t:Math.min(t,a));if(!Number.isInteger(n)||n<0)throw new RangeError(`invalid ncol (got ${n})`);if(o.pivot.some((s,i)=>s!==i+1)&&n<a)throw new RangeError("ncol must be at least the number of columns because the decomposition is pivoted");let u=M(t,n);for(let s=0;s<n;s++)if(s<a)for(let i=0;i<=Math.min(s,t-1);i++)u.data[i+s*t]=o.a.data[i+s*t];else s<t&&(u.data[s+s*t]=1);y(o,u,!1);let h=Math.min(n,a),f=M(t,n);f.data.set(u.data);for(let s=0;s<h;s++){let i=o.pivot[s]-1;i<h&&f.data.set(u.data.subarray(s*t,(s+1)*t),i*t)}return d(f)}function tt(c,r,o={}){let t=Array.isArray(c)?_(c,{tol:o.tol??1e-7}):c,a=t.qr.length,e=a===0?0:t.qr[0].length;if(t.rank!==Math.min(a,e))throw new Error("singular matrix in qrSolve");if(r===void 0&&a!==e)throw new TypeError("only square matrices can be inverted");let n=r??Array.from({length:a},(h,f)=>Array.from({length:a},(s,i)=>f===i?1:0)),l=W(t,n),u=h=>Number.isNaN(h)?0:h;return E(n)?l.map(h=>h.map(u)):l.map(u)}function nt(c,r={}){let o=x(c);if(R(o),o.nrow===0)throw new RangeError("the matrix has zero dimension");if(r.pivot){let{pivot:a,rank:e}=P(o,r.tol??-1);return I(o),{r:d(o),pivot:a.map(n=>n-1),rank:e}}let t=C(o);if(t>0)throw new Error(`the matrix is not positive definite: the leading minor of order ${t} is not positive`);return I(o),d(o)}function I(c){let r=c.nrow;for(let o=0;o<r;o++)for(let t=o+1;t<r;t++)c.data[t+o*r]=0}function C(c){let r=c.nrow,o=c.data;for(let t=0;t<r;t++){let a=t*r,e=o[t+a];for(let n=0;n<t;n++)e-=o[n+a]*o[n+a];if(e<=0)return o[t+a]=e,t+1;e=Math.sqrt(e),o[t+a]=e;for(let n=t+1;n<r;n++){let l=n*r,u=o[t+l];for(let h=0;h<t;h++)u-=o[h+a]*o[h+l];o[t+l]=u/e}}return 0}function P(c,r){let o=c.nrow,t=c.data,a=Array.from({length:o},(s,i)=>i+1),e=(s,i)=>s+i*o,n=(s,i)=>{let p=t[s];t[s]=t[i],t[i]=p},l=0;for(let s=1;s<o;s++)t[e(s,s)]>t[e(l,l)]&&(l=s);let u=t[e(l,l)];if(u<=0||Number.isNaN(u))return{pivot:a,rank:0};let h=r<0?o*Number.EPSILON*u:r,f=new Float64Array(2*o);for(let s=0;s<o;s++){for(let i=s;i<o;i++)s>0&&(f[i]+=t[e(s-1,i)]**2),f[o+i]=t[e(i,i)]-f[i];if(s>0){l=s;for(let i=s+1;i<o;i++)f[o+i]>f[o+l]&&(l=i);if(u=f[o+l],u<=h||Number.isNaN(u))return t[e(s,s)]=u,{pivot:a,rank:s}}if(s!==l){t[e(l,l)]=t[e(s,s)];for(let i=0;i<s;i++)n(e(i,s),e(i,l));for(let i=l+1;i<o;i++)n(e(s,i),e(l,i));for(let i=s+1;i<l;i++)n(e(s,i),e(i,l));[f[s],f[l]]=[f[l],f[s]],[a[s],a[l]]=[a[l],a[s]]}u=Math.sqrt(u),t[e(s,s)]=u;for(let i=s+1;i<o;i++){let p=t[e(s,i)];for(let m=0;m<s;m++)p-=t[e(m,s)]*t[e(m,i)];t[e(s,i)]=p/u}}return{pivot:a,rank:o}}function et(c,r={}){let o=A(c),t=r.size??o.ncol;if(!Number.isInteger(t)||t<1)throw new RangeError(`size must be a positive integer (got ${t})`);if(t>o.ncol)throw new RangeError(`size cannot exceed the number of columns (${o.ncol})`);if(t>o.nrow)throw new RangeError(`size cannot exceed the number of rows (${o.nrow})`);let a=M(t,t);for(let e=0;e<t;e++)for(let n=0;n<=e;n++)a.data[n+e*t]=o.data[n+e*o.nrow];X(a);for(let e=0;e<t;e++)for(let n=e+1;n<t;n++)a.data[n+e*t]=a.data[e+n*t];return d(a)}function X(c){let r=c.nrow,o=c.data;for(let t=0;t<r;t++)if(o[t+t*r]===0)throw new Error(`element (${t+1}, ${t+1}) is zero, so the inverse cannot be computed`);for(let t=0;t<r;t++){let a=t*r;o[t+a]=1/o[t+a];let e=-o[t+a];for(let n=0;n<t;n++){let l=o[n+a];if(l!==0){for(let u=0;u<n;u++)o[u+a]+=l*o[u+n*r];o[n+a]=l*o[n+n*r]}}for(let n=0;n<t;n++)o[n+a]*=e}for(let t=0;t<r;t++){let a=o[t+t*r];if(t<r-1){let e=0;for(let n=t;n<r;n++)e+=o[t+n*r]*o[t+n*r];o[t+t*r]=e;for(let n=0;n<t;n++)o[n+t*r]*=a;for(let n=t+1;n<r;n++){let l=o[t+n*r];if(l!==0)for(let u=0;u<t;u++)o[u+t*r]+=l*o[u+n*r]}}else for(let e=0;e<=t;e++)o[e+t*r]*=a}}export{M as a,E as b,x as c,A as d,d as e,B as f,R as g,_ as h,T as i,z as j,H as k,J as l,W as m,K as n,U as o,V as p,Y as q,Z as r,tt as s,nt as t,C as u,et as v,X as w};
|
package/dist/data/grouping.d.ts
CHANGED
|
@@ -81,9 +81,12 @@ export type AggregateValue = number | readonly number[] | Readonly<Record<string
|
|
|
81
81
|
* The function applied to the values of each group, as a data frame. Equivalent to R's `aggregate()`.
|
|
82
82
|
*
|
|
83
83
|
* Formula form, `aggregate(formula, data, fun)`: `"y ~ g"`, `"y ~ g + h"`, `"cbind(y, z) ~ g"` or `". ~ g"` (every
|
|
84
|
-
* column not on the right)
|
|
85
|
-
*
|
|
86
|
-
*
|
|
84
|
+
* column not on the right). The grouping variables are all the variables of the right-hand side in order of first
|
|
85
|
+
* appearance, whatever its operators (`"y ~ g:h"` and `"y ~ g * h"` group by g and h); `"y ~ ."` groups by every
|
|
86
|
+
* column not summarised, and `"y ~ 1"` gives one row without a grouping column. The rows with a missing value in any
|
|
87
|
+
* variable of the formula are dropped first. Data frame form, `aggregate(x, by, fun)`: the columns of `x` summarised
|
|
88
|
+
* by the label columns of `by` (its keys name them); only the rows with a missing label are dropped, so `fun` sees the
|
|
89
|
+
* missing values of `x`.
|
|
87
90
|
*
|
|
88
91
|
* The result has the grouping columns first (with the labels as in the data), then one column per summarised column,
|
|
89
92
|
* and one row per non-empty combination of the groups (the first factor varying fastest). When `fun` returns k > 1
|
package/dist/data/grouping.js
CHANGED
|
@@ -2,18 +2,21 @@
|
|
|
2
2
|
//
|
|
3
3
|
// Written for rStats.js (no ported code) from oracle/grouping-behaviour.md. Group labels are turned into factors with
|
|
4
4
|
// the library's level rules: the sorted distinct non-missing values (numbers by value, strings by code point, FALSE
|
|
5
|
-
// before TRUE). With several factors the groups are the cells of their cross classification in column-major order
|
|
5
|
+
// before TRUE); numbers with the same 15-digit text are one level, as in R's factor() (src/internal/levels.ts). With several factors the groups are the cells of their cross classification in column-major order
|
|
6
6
|
// (the first factor varies fastest). A row whose label is missing (null, or NaN in a numeric column) belongs to no
|
|
7
7
|
// group. tapply keeps the empty cells (NaN or null), split keeps them unless `drop`, aggregate leaves them out.
|
|
8
|
+
// aggregate's grouping columns hold the labels of each group's first row, which for numbers may differ from the
|
|
9
|
+
// level's value.
|
|
8
10
|
import { formatR } from "../htest/core/simulate.js";
|
|
9
|
-
import {
|
|
11
|
+
import { numberLevels } from "../internal/levels.js";
|
|
12
|
+
import { expandRhs, formulaVariables, parseFormula } from "../models/formula.js";
|
|
10
13
|
import { compareCodePoints } from "../models/modelFrame.js";
|
|
11
14
|
const isMissing = (v) => v === null || (typeof v === "number" && Number.isNaN(v));
|
|
12
15
|
const levelOrder = (a, b) => typeof a === "number" ? a - b : typeof a === "string" ? compareCodePoints(a, b) : Number(a) - Number(b);
|
|
13
16
|
/** A level as R names it: numbers as as.character (15 significant digits), booleans as TRUE and FALSE */
|
|
14
17
|
const levelName = (v) => typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : typeof v === "string" ? v : Number.isFinite(v) ? formatR(v) : v > 0 ? "Inf" : "-Inf";
|
|
15
18
|
function factorOf(name, labels) {
|
|
16
|
-
const vals =
|
|
19
|
+
const vals = numberLevels(labels); // numbers by their text; -0 is the label 0
|
|
17
20
|
const kinds = new Set(vals.filter((v) => !isMissing(v)).map((v) => typeof v));
|
|
18
21
|
if (kinds.size > 1)
|
|
19
22
|
throw new TypeError(`${name} mixes ${[...kinds].join(" and ")} labels`);
|
|
@@ -166,21 +169,12 @@ function labelColumn(data, name) {
|
|
|
166
169
|
throw new TypeError(`column '${name}' must be an array`);
|
|
167
170
|
return col;
|
|
168
171
|
}
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
summands(node.right, out);
|
|
176
|
-
}
|
|
177
|
-
else if (node.type === "paren")
|
|
178
|
-
summands(node.arg, out);
|
|
179
|
-
else
|
|
180
|
-
throw new SyntaxError("invalid formula: the right-hand side must be grouping variables joined by '+'");
|
|
181
|
-
return out;
|
|
182
|
-
}
|
|
183
|
-
/** The summarised and the grouping columns of `y ~ g`, `y ~ g + h`, `cbind(y, z) ~ g` or `. ~ g` */
|
|
172
|
+
/**
|
|
173
|
+
* The summarised and the grouping columns of a formula: the grouping columns are all the variables of the right-hand
|
|
174
|
+
* side in order of first appearance, whatever its operators (`y ~ g:h`, `y ~ g*h` and `y ~ g + h - g` all group by g
|
|
175
|
+
* and h; `y ~ 1` by nothing); `.` on the right stands for every column not summarised, on the left for every column
|
|
176
|
+
* not on the right.
|
|
177
|
+
*/
|
|
184
178
|
function aggregateFormula(formula, columns) {
|
|
185
179
|
if (typeof formula !== "string")
|
|
186
180
|
throw new TypeError("the formula must be a string");
|
|
@@ -188,22 +182,28 @@ function aggregateFormula(formula, columns) {
|
|
|
188
182
|
if (tilde < 0)
|
|
189
183
|
throw new SyntaxError("invalid formula: missing '~'");
|
|
190
184
|
const lhs = formula.slice(0, tilde).trim();
|
|
191
|
-
const
|
|
185
|
+
const { rhs } = parseFormula(`~ ${formula.slice(tilde + 1)}`);
|
|
192
186
|
const name = /^[A-Za-z.][A-Za-z0-9._]*$/;
|
|
193
187
|
let values;
|
|
194
|
-
if (lhs
|
|
195
|
-
values = columns.filter((c) => !groups.includes(c));
|
|
196
|
-
else {
|
|
188
|
+
if (lhs !== ".") {
|
|
197
189
|
const m = /^cbind\s*\((.*)\)$/s.exec(lhs);
|
|
198
190
|
values = m === null ? [lhs] : m[1].split(",").map((s) => s.trim());
|
|
199
191
|
if (values.some((v) => !name.test(v) || v === ".")) {
|
|
200
192
|
throw new SyntaxError("invalid formula: the left-hand side must be a variable, cbind(...) of variables or '.'");
|
|
201
193
|
}
|
|
202
194
|
}
|
|
203
|
-
|
|
195
|
+
else if (formulaVariables(rhs, []).length < formulaVariables(rhs, ["."]).length) {
|
|
196
|
+
throw new SyntaxError("invalid formula: '.' cannot be on both sides");
|
|
197
|
+
}
|
|
198
|
+
const dot = values === undefined ? [] : columns.filter((c) => !values.includes(c));
|
|
199
|
+
const groups = formulaVariables(rhs, dot);
|
|
200
|
+
// (the expansion's errors, such as a number that is not a term or an invalid power, as R's terms())
|
|
201
|
+
expandRhs(rhs, () => 0, dot);
|
|
202
|
+
return { values: values ?? columns.filter((c) => !groups.includes(c)), groups };
|
|
204
203
|
}
|
|
205
204
|
function aggregateRows(valueNames, valueCols, groupNames, groupCols, keep, fun) {
|
|
206
|
-
|
|
205
|
+
// (y ~ 1: no grouping column, one group of all the rows)
|
|
206
|
+
const n = groupCols[0]?.length ?? valueCols[0]?.length ?? 0;
|
|
207
207
|
valueNames.forEach((v, j) => {
|
|
208
208
|
if (valueCols[j].length !== n)
|
|
209
209
|
throw new RangeError(`variable lengths differ (found for '${v}')`);
|
|
@@ -211,9 +211,13 @@ function aggregateRows(valueNames, valueCols, groupNames, groupCols, keep, fun)
|
|
|
211
211
|
const g = groupingOf(groupCols, groupNames, n);
|
|
212
212
|
const cells = rowsByCell(g).map((rows, cell) => ({ cell, rows: rows.filter(keep) })).filter((c) => c.rows.length > 0);
|
|
213
213
|
const out = {};
|
|
214
|
-
|
|
214
|
+
// The labels of each group's first row (-0 as 0), as R keeps them
|
|
215
215
|
groupNames.forEach((name, j) => {
|
|
216
|
-
|
|
216
|
+
const col = groupCols[j];
|
|
217
|
+
out[name] = cells.map((c) => {
|
|
218
|
+
const v = col[c.rows[0]];
|
|
219
|
+
return v === 0 ? 0 : v;
|
|
220
|
+
});
|
|
217
221
|
});
|
|
218
222
|
valueNames.forEach((name, j) => {
|
|
219
223
|
const col = valueCols[j];
|
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Written for rStats.js (no ported code). R accumulates sums and products in long double (64-bit mantissa) and
|
|
5
5
|
// rounds once at the end; here they are accumulated in double-double (106 bits) and rounded once, which gives the
|
|
6
|
-
// correctly rounded result in the same cases and more.
|
|
7
|
-
//
|
|
6
|
+
// correctly rounded result in the same cases and more. Intermediate values beyond the double range do not overflow
|
|
7
|
+
// (as long double's wider exponent avoids in R): sums continue on values scaled by a power of 2 once they would
|
|
8
|
+
// overflow (src/internal/summary.ts), and products keep a separate power-of-two exponent, with factors far from 1
|
|
9
|
+
// scaled before they are multiplied.
|
|
8
10
|
// As everywhere in rStats.js, NaN stands for R's NA: with `naRm` it is dropped, otherwise it propagates.
|
|
9
|
-
import { mean as meanOf, meanDD, variance as varianceOf } from "../internal/summary.js";
|
|
10
|
-
import {
|
|
11
|
+
import { ldexp, mean as meanOf, meanDD, sum as sumOf, variance as varianceOf, wideSum, wideSumAdd, wideSumValue, } from "../internal/summary.js";
|
|
12
|
+
import { ddMul } from "../special/dd.js";
|
|
11
13
|
/** The values as an array, NaN dropped when naRm; undefined when a NaN remains (the result is then NaN) */
|
|
12
14
|
export function values(x, naRm) {
|
|
13
15
|
const xs = Array.from(x);
|
|
@@ -15,15 +17,6 @@ export function values(x, naRm) {
|
|
|
15
17
|
return xs.filter((v) => !Number.isNaN(v));
|
|
16
18
|
return xs.some(Number.isNaN) ? undefined : xs;
|
|
17
19
|
}
|
|
18
|
-
/** Sum of finite values in double-double; with infinities the plain sum (Inf, -Inf or NaN) */
|
|
19
|
-
function sumOf(xs) {
|
|
20
|
-
if (!xs.every(Number.isFinite))
|
|
21
|
-
return xs.reduce((a, b) => a + b, 0);
|
|
22
|
-
let s = [0, 0];
|
|
23
|
-
for (const v of xs)
|
|
24
|
-
s = ddAdd(s, [v, 0]);
|
|
25
|
-
return s[0] + s[1];
|
|
26
|
-
}
|
|
27
20
|
/**
|
|
28
21
|
* Sum of the values. Equivalent to R's `sum()`. For a numeric vector (0 for an empty one).
|
|
29
22
|
*
|
|
@@ -52,21 +45,40 @@ export function prod(x, options = {}) {
|
|
|
52
45
|
const xs = values(x, options.naRm);
|
|
53
46
|
if (xs === undefined)
|
|
54
47
|
return NaN;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const k = Math.floor(Math.log2(Math.abs(p[0])));
|
|
63
|
-
if (k > 500 || k < -500) {
|
|
64
|
-
const f = 2 ** -k;
|
|
65
|
-
p = [p[0] * f, p[1] * f];
|
|
66
|
-
e += k;
|
|
67
|
-
}
|
|
48
|
+
const acc = wideProd();
|
|
49
|
+
for (let i = 0; i < xs.length; i++) {
|
|
50
|
+
const v = xs[i];
|
|
51
|
+
// A zero or infinite factor fixes the magnitude: the sign of the product so far times the remaining factors
|
|
52
|
+
if (!Number.isFinite(v) || v === 0)
|
|
53
|
+
return xs.slice(i).reduce((a, b) => a * b, prodSign(acc));
|
|
54
|
+
wideProdMul(acc, v);
|
|
68
55
|
}
|
|
69
|
-
return scaled(p, e);
|
|
56
|
+
return scaled(acc.p, acc.e);
|
|
57
|
+
}
|
|
58
|
+
function wideProd() {
|
|
59
|
+
return { p: [1, 0], e: 0 };
|
|
60
|
+
}
|
|
61
|
+
/** Multiplies acc by the finite non-zero v */
|
|
62
|
+
function wideProdMul(acc, v) {
|
|
63
|
+
// A factor far from 1 is scaled near 1 first (exactly), so that the product and its splitting cannot overflow
|
|
64
|
+
// and its low word cannot underflow
|
|
65
|
+
let k = Math.floor(Math.log2(Math.abs(v)));
|
|
66
|
+
if (k > 500 || k < -500) {
|
|
67
|
+
v = ldexp(v, -k);
|
|
68
|
+
acc.e += k;
|
|
69
|
+
}
|
|
70
|
+
let p = ddMul(acc.p, [v, 0]);
|
|
71
|
+
k = Math.floor(Math.log2(Math.abs(p[0])));
|
|
72
|
+
if (k > 500 || k < -500) {
|
|
73
|
+
const f = 2 ** -k;
|
|
74
|
+
p = [p[0] * f, p[1] * f];
|
|
75
|
+
acc.e += k;
|
|
76
|
+
}
|
|
77
|
+
acc.p = p;
|
|
78
|
+
}
|
|
79
|
+
/** ±1, the sign of the product */
|
|
80
|
+
function prodSign(acc) {
|
|
81
|
+
return acc.p[0] < 0 ? -1 : 1;
|
|
70
82
|
}
|
|
71
83
|
/**
|
|
72
84
|
* Arithmetic mean, optionally trimmed. Equivalent to R's `mean()`. Accurate to the last bit: the sum is taken in
|
|
@@ -217,20 +229,21 @@ export function range(x, options = {}) {
|
|
|
217
229
|
* @category Descriptive statistics
|
|
218
230
|
*/
|
|
219
231
|
export function cumsum(x) {
|
|
232
|
+
const xs = Array.from(x);
|
|
220
233
|
const out = [];
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
let
|
|
224
|
-
for (const v of
|
|
225
|
-
plain
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
exact = false;
|
|
232
|
-
out.push(Number.isNaN(v) || Number.isNaN(plain) ? NaN : plain);
|
|
234
|
+
const acc = wideSum();
|
|
235
|
+
// From the first value that is not finite on, the sums are ±Inf or NaN whatever the finite sum before it
|
|
236
|
+
let plain;
|
|
237
|
+
for (const v of xs) {
|
|
238
|
+
if (plain === undefined && !Number.isFinite(v))
|
|
239
|
+
plain = 0;
|
|
240
|
+
if (plain !== undefined) {
|
|
241
|
+
plain += v;
|
|
242
|
+
out.push(plain);
|
|
243
|
+
continue;
|
|
233
244
|
}
|
|
245
|
+
wideSumAdd(acc, v, xs.length);
|
|
246
|
+
out.push(wideSumValue(acc));
|
|
234
247
|
}
|
|
235
248
|
return out;
|
|
236
249
|
}
|
|
@@ -248,24 +261,19 @@ export function cumsum(x) {
|
|
|
248
261
|
export function cumprod(x) {
|
|
249
262
|
const out = [];
|
|
250
263
|
// exact while the factors are finite and non-zero: double-double mantissa times 2^e
|
|
251
|
-
|
|
252
|
-
|
|
264
|
+
const acc = wideProd();
|
|
265
|
+
// From the first zero or non-finite factor on, the products are ±0, ±Inf or NaN: the sign so far times the factors
|
|
253
266
|
let plain;
|
|
254
267
|
for (const v of Array.from(x)) {
|
|
255
268
|
if (plain === undefined && (!Number.isFinite(v) || v === 0))
|
|
256
|
-
plain =
|
|
269
|
+
plain = prodSign(acc);
|
|
257
270
|
if (plain !== undefined) {
|
|
258
271
|
plain *= v;
|
|
259
272
|
out.push(plain);
|
|
260
273
|
continue;
|
|
261
274
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
if (k > 500 || k < -500) {
|
|
265
|
-
p = [p[0] * 2 ** -k, p[1] * 2 ** -k];
|
|
266
|
-
e += k;
|
|
267
|
-
}
|
|
268
|
-
out.push(scaled(p, e));
|
|
275
|
+
wideProdMul(acc, v);
|
|
276
|
+
out.push(scaled(acc.p, acc.e));
|
|
269
277
|
}
|
|
270
278
|
return out;
|
|
271
279
|
}
|
package/dist/descriptive/cov.js
CHANGED
|
@@ -78,6 +78,9 @@ function compute(x, y, options, correlation) {
|
|
|
78
78
|
}
|
|
79
79
|
else if (u.some(Number.isNaN) || v.some(Number.isNaN))
|
|
80
80
|
return NaN;
|
|
81
|
+
// fewer than 2 observations (for "pairwise.complete.obs", in this pair): NaN, as in R, for every method
|
|
82
|
+
if (u.length < 2)
|
|
83
|
+
return NaN;
|
|
81
84
|
if (method === "kendall") {
|
|
82
85
|
if (correlation)
|
|
83
86
|
return kendall(u, v).tau;
|
|
@@ -88,8 +91,10 @@ function compute(x, y, options, correlation) {
|
|
|
88
91
|
return covariance(u, v);
|
|
89
92
|
};
|
|
90
93
|
const out = px.map((a) => py.map((b) => entry(a, b)));
|
|
91
|
-
// as in R, the correlation matrix of x alone has 1 on the diagonal, whatever the column holds
|
|
92
|
-
|
|
94
|
+
// as in R, the correlation matrix of x alone has 1 on the diagonal, whatever the column holds, unless fewer than 2
|
|
95
|
+
// observations are used (then it is all NaN)
|
|
96
|
+
const used = keepRows === undefined ? n : keepRows.filter(Boolean).length;
|
|
97
|
+
if (correlation && y === undefined && use !== "pairwise.complete.obs" && used >= 2)
|
|
93
98
|
out.forEach((r, i) => (r[i] = 1));
|
|
94
99
|
return (y === undefined ? false : !isMatrix(x) && !isMatrix(y)) ? out[0][0] : out;
|
|
95
100
|
}
|
|
@@ -4,6 +4,12 @@
|
|
|
4
4
|
* @category Agreement, reliability and factor analysis
|
|
5
5
|
*/
|
|
6
6
|
export type FactanalRotation = "varimax" | "promax" | "none";
|
|
7
|
+
/**
|
|
8
|
+
* Factor scores of {@link factanal}
|
|
9
|
+
*
|
|
10
|
+
* @category Agreement, reliability and factor analysis
|
|
11
|
+
*/
|
|
12
|
+
export type FactanalScores = "none" | "regression" | "Bartlett";
|
|
7
13
|
/**
|
|
8
14
|
* Options of {@link factanal}
|
|
9
15
|
*
|
|
@@ -16,6 +22,13 @@ export interface FactanalOptions {
|
|
|
16
22
|
nObs?: number;
|
|
17
23
|
/** Default `"varimax"`. */
|
|
18
24
|
rotation?: FactanalRotation;
|
|
25
|
+
/**
|
|
26
|
+
* Factor scores to compute from the data (R's `scores`): `"none"` (default), `"regression"` (Thomson's,
|
|
27
|
+
* z R^-1 L) or `"Bartlett"` (z W L (L' W L)^-1 with W = diag(1 / uniquenesses)), where z is the data
|
|
28
|
+
* standardised by column (denominator n - 1), R its correlation matrix and L the final loadings. Scores need
|
|
29
|
+
* `x`: with `covmat` they are an error.
|
|
30
|
+
*/
|
|
31
|
+
scores?: FactanalScores;
|
|
19
32
|
/** Settings of the optimisation (part of R's `control` list). */
|
|
20
33
|
control?: {
|
|
21
34
|
/** Lower bound of the uniquenesses. Default 0.005. */
|
|
@@ -34,6 +47,8 @@ export interface FactanalResult {
|
|
|
34
47
|
uniquenesses: number[];
|
|
35
48
|
/** The (rotated) loadings, p rows by `factors` columns, columns sorted by decreasing sum of squares, each column's sum positive */
|
|
36
49
|
loadings: number[][];
|
|
50
|
+
/** The factor scores (with `scores` other than `"none"`): one row per observation, one column per factor */
|
|
51
|
+
scores?: number[][];
|
|
37
52
|
/** The rotation matrix (absent for `rotation: "none"` and for one factor) */
|
|
38
53
|
rotmat?: number[][];
|
|
39
54
|
/** The likelihood-ratio statistic (NaN without n.obs or with no degrees of freedom) */
|
|
@@ -69,6 +84,7 @@ export declare function varimax(L: readonly (readonly number[])[]): {
|
|
|
69
84
|
* const fa = factanal(null, 1, { covmat: R });
|
|
70
85
|
* fa.uniquenesses; // [0.19, 0.36, 0.51]
|
|
71
86
|
* fa.loadings; // [[0.9], [0.8], [0.7]]
|
|
87
|
+
* // Factor scores need the data: factanal(x, 1, { scores: "regression" }).scores (one row per row of x)
|
|
72
88
|
* ```
|
|
73
89
|
*
|
|
74
90
|
* @category Agreement, reliability and factor analysis
|
|
@@ -103,14 +103,21 @@ function promax(L) {
|
|
|
103
103
|
* const fa = factanal(null, 1, { covmat: R });
|
|
104
104
|
* fa.uniquenesses; // [0.19, 0.36, 0.51]
|
|
105
105
|
* fa.loadings; // [[0.9], [0.8], [0.7]]
|
|
106
|
+
* // Factor scores need the data: factanal(x, 1, { scores: "regression" }).scores (one row per row of x)
|
|
106
107
|
* ```
|
|
107
108
|
*
|
|
108
109
|
* @category Agreement, reliability and factor analysis
|
|
109
110
|
*/
|
|
110
111
|
export function factanal(x, factors, options = {}) {
|
|
112
|
+
const scores = options.scores ?? "none";
|
|
113
|
+
if (scores !== "none" && scores !== "regression" && scores !== "Bartlett") {
|
|
114
|
+
throw new RangeError("'arg' should be one of “none”, “regression”, “Bartlett”");
|
|
115
|
+
}
|
|
111
116
|
let cv;
|
|
112
117
|
let nObs;
|
|
113
118
|
if (options.covmat !== undefined) {
|
|
119
|
+
if (scores !== "none")
|
|
120
|
+
throw new RangeError("requested scores without an 'x' matrix");
|
|
114
121
|
cv = options.covmat.map((r) => r.slice());
|
|
115
122
|
nObs = options.nObs ?? NaN;
|
|
116
123
|
}
|
|
@@ -184,7 +191,26 @@ export function factanal(x, factors, options = {}) {
|
|
|
184
191
|
objective: fit.value,
|
|
185
192
|
counts: fit.counts,
|
|
186
193
|
};
|
|
194
|
+
if (scores !== "none")
|
|
195
|
+
out.scores = factorScores(x, S, psi, L, scores);
|
|
187
196
|
if (rotmat !== undefined)
|
|
188
197
|
out.rotmat = rotmat;
|
|
189
198
|
return out;
|
|
190
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Factor scores from the data x standardised by column (z), the correlation matrix S, the uniquenesses psi and the
|
|
202
|
+
* final loadings L: regression (Thomson) z S^-1 L, or Bartlett z W L (L' W L)^-1 with W = diag(1 / psi). No factor
|
|
203
|
+
* covariance enters (none is defined for the varimax and promax rotations)
|
|
204
|
+
*/
|
|
205
|
+
function factorScores(x, S, psi, L, method) {
|
|
206
|
+
const n = x.length;
|
|
207
|
+
const means = x[0].map((_, j) => sumOnce(x.map((r) => r[j])) / n);
|
|
208
|
+
const centred = x.map((r) => r.map((v, j) => v - means[j]));
|
|
209
|
+
const sds = colSumsOf(centred, (v) => v * v).map((s) => Math.sqrt(s / (n - 1)));
|
|
210
|
+
const z = centred.map((r) => r.map((v, j) => v / sds[j]));
|
|
211
|
+
if (method === "regression")
|
|
212
|
+
return matMul(z, solve(S, L));
|
|
213
|
+
const WL = L.map((r, i) => r.map((v) => v / psi[i]));
|
|
214
|
+
// (L' W L)^-1 is symmetric, so W L (L' W L)^-1 is the transpose of solve(L' W L, (W L)')
|
|
215
|
+
return matMul(z, transpose(solve(matMul(transpose(L), WL), transpose(WL))));
|
|
216
|
+
}
|
|
@@ -5,9 +5,15 @@ import type { Sample } from "../htest/types.js";
|
|
|
5
5
|
* @category Descriptive statistics
|
|
6
6
|
*/
|
|
7
7
|
export interface PrettyOptions {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* Desired number of intervals. Default `5`. Truncated towards 0 to an integer (as in R); `NaN`, a negative value
|
|
10
|
+
* or one of 2^31 or more in absolute value is an error (unless `x` has no finite values).
|
|
11
|
+
*/
|
|
9
12
|
n?: number;
|
|
10
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* Minimal number of intervals. Default `n / 3` rounded down (computed from `n` before it is truncated). Truncated
|
|
15
|
+
* towards 0 to an integer (as in R); `NaN`, a negative value or one greater than `n` is an error.
|
|
16
|
+
*/
|
|
11
17
|
minN?: number;
|
|
12
18
|
/** Factor applied to the cell when the range is very small. Default `0.75`. */
|
|
13
19
|
shrinkSml?: number;
|
package/dist/descriptive/hist.js
CHANGED
|
@@ -26,8 +26,16 @@ export function pretty(x, options = {}) {
|
|
|
26
26
|
const finite = Array.from(x).filter(Number.isFinite);
|
|
27
27
|
if (finite.length === 0)
|
|
28
28
|
return [];
|
|
29
|
-
|
|
30
|
-
const
|
|
29
|
+
// R converts n and minN to integers (truncating towards 0) and checks them in this order
|
|
30
|
+
const nGiven = options.n ?? 5;
|
|
31
|
+
if (Number.isNaN(nGiven) || Math.abs(nGiven) >= 2 ** 31 || Math.trunc(nGiven) < 0)
|
|
32
|
+
throw new RangeError("invalid 'n' argument");
|
|
33
|
+
const n = Math.trunc(nGiven);
|
|
34
|
+
const minNGiven = options.minN ?? Math.floor(nGiven / 3);
|
|
35
|
+
if (Number.isNaN(minNGiven) || Math.trunc(minNGiven) < 0 || Math.trunc(minNGiven) > n) {
|
|
36
|
+
throw new RangeError("invalid 'min.n' argument");
|
|
37
|
+
}
|
|
38
|
+
const minN = Math.trunc(minNGiven);
|
|
31
39
|
const shrink = options.shrinkSml ?? 0.75;
|
|
32
40
|
const h = options.highUBias ?? 1.5;
|
|
33
41
|
const h5 = options.u5Bias ?? 0.5 + 1.5 * h;
|
|
@@ -55,13 +55,18 @@ export declare function fivenum(x: Sample): [number, number, number, number, num
|
|
|
55
55
|
* @category Descriptive statistics
|
|
56
56
|
*/
|
|
57
57
|
export interface MadOptions extends NaRmOptions {
|
|
58
|
-
/** Centre. Default: the median. */
|
|
58
|
+
/** Centre. Default: the median (`NaN` if `x` has a missing value and `naRm` is not set). */
|
|
59
59
|
center?: number;
|
|
60
60
|
/** Scale factor. Default `1.4826` (consistent for the normal standard deviation). */
|
|
61
61
|
constant?: number;
|
|
62
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* For an even count n, take the lower of the two middle absolute deviations (the "lo-median"): the (n / 2)-th
|
|
64
|
+
* smallest. As in R, n counts the missing values unless `naRm` removed them, the k-th smallest is taken among
|
|
65
|
+
* the deviations that are not missing, and fewer than k of them (or k = 0) is an error. With an odd count the
|
|
66
|
+
* ordinary median is used.
|
|
67
|
+
*/
|
|
63
68
|
low?: boolean;
|
|
64
|
-
/** For an even count, take the higher one (the "hi-median"). */
|
|
69
|
+
/** For an even count n, take the higher one (the "hi-median"): the (n / 2 + 1)-th smallest, as for `low`. Both `low` and `high` is an error for an even count. */
|
|
65
70
|
high?: boolean;
|
|
66
71
|
}
|
|
67
72
|
/**
|
|
@@ -129,20 +129,24 @@ export function fivenum(x) {
|
|
|
129
129
|
* @category Descriptive statistics
|
|
130
130
|
*/
|
|
131
131
|
export function mad(x, options = {}) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const
|
|
132
|
+
// Missing values stay in (and count in n) unless naRm removes them, as in R
|
|
133
|
+
const given = Array.from(x);
|
|
134
|
+
const xs = given.filter((v) => !Number.isNaN(v));
|
|
135
|
+
const all = options.naRm ? xs : given;
|
|
136
|
+
const center = options.center ?? (all.length > xs.length ? NaN : median(xs));
|
|
136
137
|
const constant = options.constant ?? 1.4826;
|
|
137
138
|
const low = options.low ?? false;
|
|
138
139
|
const high = options.high ?? false;
|
|
139
|
-
const dev =
|
|
140
|
+
const dev = all.map((v) => Math.abs(v - center));
|
|
140
141
|
const n = dev.length;
|
|
141
142
|
if ((low || high) && n % 2 === 0) {
|
|
142
143
|
if (low && high)
|
|
143
144
|
throw new RangeError("'low' and 'high' cannot be both TRUE");
|
|
145
|
+
// The k-th smallest among the deviations that are not missing (R's partial sort drops the missing ones)
|
|
144
146
|
const k = n / 2 + (high ? 1 : 0);
|
|
145
|
-
const s = dev.sort((a, b) => a - b);
|
|
147
|
+
const s = dev.filter((v) => !Number.isNaN(v)).sort((a, b) => a - b);
|
|
148
|
+
if (k === 0 || s.length < k)
|
|
149
|
+
throw new RangeError(`'partial' index ${k} outside bounds`);
|
|
146
150
|
return constant * s[k - 1];
|
|
147
151
|
}
|
|
148
152
|
return constant * median(dev);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Sample } from "../htest/types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Counts of the integers 1..nbins in `bin` (values truncated towards 0; others and NaN are not counted).
|
|
4
|
-
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin).
|
|
4
|
+
* Equivalent to R's `tabulate()`. `nbins` defaults to max(1, bin) and is truncated towards 0, as R does.
|
|
5
5
|
*
|
|
6
6
|
* @example
|
|
7
7
|
* ```ts
|
|
@@ -23,7 +23,8 @@ export interface TableOptions {
|
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
25
|
* Frequency table of the distinct values. Equivalent to R's `table()`. For one numeric vector: `values` in increasing
|
|
26
|
-
* order (NaN last when counted) with their `counts`.
|
|
26
|
+
* order (NaN last when counted) with their `counts`. As in R, values with the same text (15 significant digits, as
|
|
27
|
+
* R's `as.character`) are counted as one, under the smallest of them.
|
|
27
28
|
*
|
|
28
29
|
* @example
|
|
29
30
|
* ```ts
|
|
@@ -63,8 +64,9 @@ export interface CutOptions {
|
|
|
63
64
|
/**
|
|
64
65
|
* Interval numbers (1-based) of the values, or NaN outside the breaks. Equivalent to R's `cut(..., labels = FALSE)`.
|
|
65
66
|
*
|
|
66
|
-
* @param breaks The break points
|
|
67
|
-
* widened by 1/1000 of the range at
|
|
67
|
+
* @param breaks The break points (NaN among them is dropped, as R does; fewer than 2 left give NaN codes), or a
|
|
68
|
+
* number of intervals (at least 2): then equal intervals over the range of `x`, widened by 1/1000 of the range at
|
|
69
|
+
* each end, as R does. That range must be finite.
|
|
68
70
|
*
|
|
69
71
|
* @example
|
|
70
72
|
* ```ts
|
|
@@ -83,7 +85,7 @@ export declare function cut(x: Sample, breaks: number | readonly number[], optio
|
|
|
83
85
|
export interface FindIntervalOptions {
|
|
84
86
|
/** Treat the last interval as closed on the right (with `leftOpen`, the first as closed on the left). */
|
|
85
87
|
rightmostClosed?: boolean;
|
|
86
|
-
/**
|
|
88
|
+
/** Give 1 instead of 0 left of the first point and N - 1 instead of N at or right of the last (N = `vec.length`). */
|
|
87
89
|
allInside?: boolean;
|
|
88
90
|
/** Intervals (v_i, v_(i+1)] instead of [v_i, v_(i+1)). */
|
|
89
91
|
leftOpen?: boolean;
|