@numero-uno-jpn/rstats 0.5.0 → 0.7.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 (179) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.ja.md +36 -20
  3. package/README.md +34 -18
  4. package/THIRD_PARTY_NOTICES.md +25 -5
  5. package/dist/chunks/chunk-6R7YDHA2.js +2 -0
  6. package/dist/chunks/chunk-AFKYWGKN.js +2 -0
  7. package/dist/chunks/chunk-ANYGLFT4.js +2 -0
  8. package/dist/chunks/chunk-BI5RSUZ2.js +2 -0
  9. package/dist/chunks/chunk-J3SNI7KY.js +2 -0
  10. package/dist/chunks/chunk-JCZAB6C5.js +2 -0
  11. package/dist/chunks/chunk-MVG5LUZU.js +2 -0
  12. package/dist/chunks/chunk-PTPPP4TI.js +2 -0
  13. package/dist/chunks/chunk-QNQJA6KZ.js +2 -0
  14. package/dist/chunks/chunk-SXSJXDD3.js +2 -0
  15. package/dist/chunks/chunk-UIOAWLAN.js +2 -0
  16. package/dist/chunks/chunk-XYXHHF5L.js +2 -0
  17. package/dist/chunks/chunk-YKN6OGJL.js +2 -0
  18. package/dist/chunks/chunk-ZW52Z3GY.js +2 -0
  19. package/dist/chunks/chunk-ZYA4ISAT.js +2 -0
  20. package/dist/descriptive/basic.d.ts +73 -0
  21. package/dist/descriptive/basic.js +256 -0
  22. package/dist/descriptive/cov.d.ts +39 -0
  23. package/dist/descriptive/cov.js +105 -0
  24. package/dist/descriptive/hist.d.ts +64 -0
  25. package/dist/descriptive/hist.js +304 -0
  26. package/dist/descriptive/moments.d.ts +63 -0
  27. package/dist/descriptive/moments.js +158 -0
  28. package/dist/descriptive/quantile.d.ts +50 -0
  29. package/dist/descriptive/quantile.js +131 -0
  30. package/dist/descriptive/rank.d.ts +23 -0
  31. package/dist/descriptive/rank.js +72 -0
  32. package/dist/descriptive/table.d.ts +54 -0
  33. package/dist/descriptive/table.js +160 -0
  34. package/dist/descriptive.js +2 -0
  35. package/dist/distributions/arcsine.d.ts +24 -0
  36. package/dist/distributions/arcsine.js +73 -0
  37. package/dist/distributions/invgamma.d.ts +29 -0
  38. package/dist/distributions/invgamma.js +85 -0
  39. package/dist/distributions/kumaraswamy.d.ts +17 -0
  40. package/dist/distributions/kumaraswamy.js +96 -0
  41. package/dist/distributions/laplace.d.ts +23 -0
  42. package/dist/distributions/laplace.js +69 -0
  43. package/dist/distributions/multinomial.d.ts +24 -0
  44. package/dist/distributions/multinomial.js +70 -0
  45. package/dist/distributions/nbeta.js +28 -10
  46. package/dist/distributions/nchisq.js +20 -3
  47. package/dist/distributions/pareto.d.ts +23 -0
  48. package/dist/distributions/pareto.js +76 -0
  49. package/dist/distributions/summary.d.ts +25 -0
  50. package/dist/distributions/summary.js +289 -0
  51. package/dist/distributions/triangular.d.ts +25 -0
  52. package/dist/distributions/triangular.js +87 -0
  53. package/dist/distributions.js +2 -0
  54. package/dist/entries/descriptive.d.ts +7 -0
  55. package/dist/entries/descriptive.js +8 -0
  56. package/dist/entries/distributions.d.ts +42 -0
  57. package/dist/entries/distributions.js +42 -0
  58. package/dist/entries/linalg.d.ts +11 -0
  59. package/dist/entries/linalg.js +11 -0
  60. package/dist/entries/numerics.d.ts +8 -0
  61. package/dist/entries/numerics.js +6 -0
  62. package/dist/entries/special.d.ts +10 -0
  63. package/dist/entries/special.js +10 -0
  64. package/dist/entries/tests.d.ts +21 -0
  65. package/dist/entries/tests.js +20 -0
  66. package/dist/htest/ansariTest.d.ts +30 -0
  67. package/dist/htest/ansariTest.js +253 -0
  68. package/dist/htest/aov.d.ts +85 -0
  69. package/dist/htest/aov.js +178 -0
  70. package/dist/htest/binomTest.d.ts +36 -0
  71. package/dist/htest/binomTest.js +121 -0
  72. package/dist/htest/chisqTest.d.ts +34 -2
  73. package/dist/htest/chisqTest.js +140 -37
  74. package/dist/htest/cor.d.ts +14 -0
  75. package/dist/htest/cor.js +4 -3
  76. package/dist/htest/core/ansari.d.ts +25 -0
  77. package/dist/htest/core/ansari.js +186 -0
  78. package/dist/htest/core/kolmogorov.d.ts +26 -0
  79. package/dist/htest/core/kolmogorov.js +221 -0
  80. package/dist/htest/core/mantelhaen.d.ts +26 -0
  81. package/dist/htest/core/mantelhaen.js +145 -0
  82. package/dist/htest/core/shapiro.d.ts +24 -0
  83. package/dist/htest/core/shapiro.js +142 -0
  84. package/dist/htest/core/simulate.d.ts +2 -0
  85. package/dist/htest/core/simulate.js +16 -0
  86. package/dist/htest/core/smirnov.d.ts +20 -0
  87. package/dist/htest/core/smirnov.js +75 -0
  88. package/dist/htest/fisherTest.d.ts +12 -1
  89. package/dist/htest/fisherTest.js +187 -127
  90. package/dist/htest/groups.d.ts +20 -0
  91. package/dist/htest/groups.js +62 -0
  92. package/dist/htest/ksTest.d.ts +31 -0
  93. package/dist/htest/ksTest.js +106 -0
  94. package/dist/htest/mantelhaenTest.d.ts +26 -0
  95. package/dist/htest/mantelhaenTest.js +196 -0
  96. package/dist/htest/mcnemarTest.d.ts +26 -0
  97. package/dist/htest/mcnemarTest.js +99 -0
  98. package/dist/htest/onewayTest.d.ts +26 -0
  99. package/dist/htest/onewayTest.js +97 -0
  100. package/dist/htest/pairwise.d.ts +64 -0
  101. package/dist/htest/pairwise.js +152 -0
  102. package/dist/htest/poissonTest.d.ts +35 -0
  103. package/dist/htest/poissonTest.js +170 -0
  104. package/dist/htest/propTest.d.ts +37 -0
  105. package/dist/htest/propTest.js +164 -0
  106. package/dist/htest/rankTests.d.ts +52 -0
  107. package/dist/htest/rankTests.js +234 -0
  108. package/dist/htest/types.d.ts +2 -0
  109. package/dist/htest/types.js +6 -0
  110. package/dist/htest/varTest.d.ts +48 -0
  111. package/dist/htest/varTest.js +118 -0
  112. package/dist/htest/wilcoxTest.js +136 -174
  113. package/dist/index.d.ts +6 -50
  114. package/dist/index.js +8 -50
  115. package/dist/integrate/quadpack.d.ts +29 -0
  116. package/dist/integrate/quadpack.js +525 -0
  117. package/dist/internal/seq.d.ts +5 -0
  118. package/dist/internal/seq.js +14 -0
  119. package/dist/internal/uniroot.js +10 -71
  120. package/dist/linalg/lu.d.ts +45 -0
  121. package/dist/linalg/lu.js +88 -0
  122. package/dist/linalg/ops.d.ts +90 -0
  123. package/dist/linalg/ops.js +320 -0
  124. package/dist/linalg.js +2 -0
  125. package/dist/models/lm.d.ts +98 -0
  126. package/dist/models/lm.js +187 -0
  127. package/dist/numerics/deriv.d.ts +37 -0
  128. package/dist/numerics/deriv.js +150 -0
  129. package/dist/numerics/integrate.d.ts +91 -0
  130. package/dist/numerics/integrate.js +264 -0
  131. package/dist/numerics/interp.d.ts +103 -0
  132. package/dist/numerics/interp.js +581 -0
  133. package/dist/numerics/ode.d.ts +23 -0
  134. package/dist/numerics/ode.js +59 -0
  135. package/dist/numerics.js +2 -0
  136. package/dist/optim/localmin.d.ts +16 -0
  137. package/dist/optim/localmin.js +97 -0
  138. package/dist/random/beta.js +1 -1
  139. package/dist/random/binomial.js +1 -1
  140. package/dist/random/continuous.js +1 -1
  141. package/dist/random/extra.d.ts +33 -0
  142. package/dist/random/extra.js +62 -0
  143. package/dist/random/gamma.js +1 -1
  144. package/dist/random/hyper.js +1 -1
  145. package/dist/random/mt.js +0 -1
  146. package/dist/random/poisson.js +0 -1
  147. package/dist/random/r2dtable.d.ts +26 -0
  148. package/dist/random/r2dtable.js +153 -0
  149. package/dist/random/rank.js +1 -1
  150. package/dist/random/rng.js +1 -1
  151. package/dist/random/sample.js +1 -1
  152. package/dist/rstats.js +3 -2
  153. package/dist/special/besselIK.d.ts +38 -0
  154. package/dist/special/besselIK.js +315 -0
  155. package/dist/special/besselJY.d.ts +32 -0
  156. package/dist/special/besselJY.js +508 -0
  157. package/dist/special/besselSeries.d.ts +8 -0
  158. package/dist/special/besselSeries.js +24 -0
  159. package/dist/special/beta.js +22 -5
  160. package/dist/special/choose.d.ts +75 -0
  161. package/dist/special/choose.js +233 -0
  162. package/dist/special/erf.d.ts +28 -2
  163. package/dist/special/erf.js +37 -10
  164. package/dist/special/extra.d.ts +47 -0
  165. package/dist/special/extra.js +220 -0
  166. package/dist/special/igam.d.ts +4 -0
  167. package/dist/special/igam.js +57 -2
  168. package/dist/special/incbet.js +77 -22
  169. package/dist/special/lgammaDiff.d.ts +7 -0
  170. package/dist/special/lgammaDiff.js +16 -3
  171. package/dist/special/log1p.d.ts +53 -0
  172. package/dist/special/log1p.js +93 -0
  173. package/dist/special/psigamma.d.ts +48 -0
  174. package/dist/special/psigamma.js +318 -0
  175. package/dist/special/rCompatible.d.ts +8 -0
  176. package/dist/special/rCompatible.js +1 -0
  177. package/dist/special.js +2 -0
  178. package/dist/tests.js +3 -0
  179. package/package.json +26 -1
@@ -0,0 +1,256 @@
1
+ // Basic summaries of a numeric vector: R's sum, prod, mean (with trim), weighted.mean, var, sd, median, range,
2
+ // cumsum, cumprod, cummax, cummin and diff.
3
+ //
4
+ // Written for rStats.js (no ported code). R accumulates sums and products in long double (64-bit mantissa) and
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. Products keep a separate power-of-two exponent, so that
7
+ // intermediate values beyond the double range do not overflow (as long double's wider exponent avoids in R).
8
+ // 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 { ddAdd, ddMul } from "../special/dd.js";
11
+ /** The values as an array, NaN dropped when naRm; undefined when a NaN remains (the result is then NaN) */
12
+ export function values(x, naRm) {
13
+ const xs = Array.from(x);
14
+ if (naRm)
15
+ return xs.filter((v) => !Number.isNaN(v));
16
+ return xs.some(Number.isNaN) ? undefined : xs;
17
+ }
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
+ /**
28
+ * Sum of the values. Equivalent to R's `sum()` for a numeric vector (0 for an empty one).
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * sum([0.1, 0.2, 0.3]); // 0.6000000000000001 in plain JS addition, 0.6 here (correctly rounded)
33
+ * ```
34
+ */
35
+ export function sum(x, options = {}) {
36
+ const xs = values(x, options.naRm);
37
+ return xs === undefined ? NaN : sumOf(xs);
38
+ }
39
+ /**
40
+ * Product of the values. Equivalent to R's `prod()` (1 for an empty vector).
41
+ */
42
+ export function prod(x, options = {}) {
43
+ const xs = values(x, options.naRm);
44
+ if (xs === undefined)
45
+ return NaN;
46
+ if (!xs.every(Number.isFinite) || xs.includes(0))
47
+ return xs.reduce((a, b) => a * b, 1);
48
+ // mantissa in double-double, exponent apart: value = (h + l) 2^e
49
+ let p = [1, 0];
50
+ let e = 0;
51
+ for (const v of xs) {
52
+ p = ddMul(p, [v, 0]);
53
+ const k = Math.floor(Math.log2(Math.abs(p[0])));
54
+ if (k > 500 || k < -500) {
55
+ const f = 2 ** -k;
56
+ p = [p[0] * f, p[1] * f];
57
+ e += k;
58
+ }
59
+ }
60
+ return scaled(p, e);
61
+ }
62
+ /**
63
+ * Arithmetic mean, optionally trimmed. Equivalent to R's `mean()`. Accurate to the last bit: the sum is taken in
64
+ * double-double and corrected by the mean deviation, as R corrects its long double mean.
65
+ */
66
+ export function mean(x, options = {}) {
67
+ const xs = values(x, options.naRm);
68
+ if (xs === undefined)
69
+ return NaN;
70
+ const n = xs.length;
71
+ if (n === 0)
72
+ return NaN;
73
+ let trim = options.trim ?? 0;
74
+ if (Number.isNaN(trim))
75
+ throw new RangeError("'trim' must be numeric of length one");
76
+ if (trim > 0 && n > 0) {
77
+ if (trim >= 0.5)
78
+ return median(xs);
79
+ trim = Math.max(trim, 0);
80
+ const lo = Math.floor(n * trim);
81
+ const s = [...xs].sort((a, b) => a - b);
82
+ return meanOf(s.slice(lo, n - lo));
83
+ }
84
+ return meanOf(xs);
85
+ }
86
+ /**
87
+ * Weighted mean `sum(x w) / sum(w)`. Equivalent to R's `weighted.mean()`: values with weight 0 do not enter the
88
+ * numerator (even if infinite or NaN), and `naRm` drops missing values of `x` with their weights.
89
+ */
90
+ export function weightedMean(x, w, options = {}) {
91
+ let xs = Array.from(x);
92
+ let ws = Array.from(w);
93
+ if (xs.length !== ws.length)
94
+ throw new RangeError("'x' and 'w' must have the same length");
95
+ if (options.naRm) {
96
+ const keep = xs.map((v) => !Number.isNaN(v));
97
+ xs = xs.filter((_, i) => keep[i]);
98
+ ws = ws.filter((_, i) => keep[i]);
99
+ }
100
+ const prods = [];
101
+ for (let i = 0; i < xs.length; i++)
102
+ if (ws[i] !== 0)
103
+ prods.push(xs[i] * ws[i]);
104
+ return sumOf(prods) / sumOf(ws);
105
+ }
106
+ /**
107
+ * Sample variance (denominator n - 1). Equivalent to R's `var()` for a vector (`NaN` for fewer than 2 values); named
108
+ * `variance` because `var` cannot be a name in JavaScript. For matrices use `cov`.
109
+ */
110
+ export function variance(x, options = {}) {
111
+ const xs = values(x, options.naRm);
112
+ if (xs === undefined)
113
+ return NaN;
114
+ return varianceOf(xs);
115
+ }
116
+ /** Sample standard deviation (denominator n - 1). Equivalent to R's `sd()`. */
117
+ export function sd(x, options = {}) {
118
+ return Math.sqrt(variance(x, options));
119
+ }
120
+ /** Median of the values (the mean of the two middle ones for an even count). Equivalent to R's `median()`. */
121
+ export function median(x, options = {}) {
122
+ const xs = values(x, options.naRm);
123
+ if (xs === undefined)
124
+ return NaN;
125
+ const n = xs.length;
126
+ if (n === 0)
127
+ return NaN;
128
+ const s = [...xs].sort((a, b) => a - b);
129
+ const h = Math.floor(n / 2);
130
+ return n % 2 === 1 ? s[h] : meanDD([s[h - 1], s[h]])[0];
131
+ }
132
+ /**
133
+ * `[min, max]` of the values. Equivalent to R's `range()` (`[NaN, NaN]` with a missing value unless `naRm`;
134
+ * `[Infinity, -Infinity]` for an empty vector).
135
+ */
136
+ export function range(x, options = {}) {
137
+ const xs = values(x, options.naRm);
138
+ if (xs === undefined)
139
+ return [NaN, NaN];
140
+ let lo = Infinity;
141
+ let hi = -Infinity;
142
+ for (const v of xs) {
143
+ if (v < lo)
144
+ lo = v;
145
+ if (v > hi)
146
+ hi = v;
147
+ }
148
+ return [lo, hi];
149
+ }
150
+ /** Running sums. Equivalent to R's `cumsum()`: each partial sum is rounded from an exact accumulator; `NaN` from the first `NaN` on. */
151
+ export function cumsum(x) {
152
+ const out = [];
153
+ let s = [0, 0];
154
+ let plain = 0;
155
+ let exact = true;
156
+ for (const v of Array.from(x)) {
157
+ plain += v;
158
+ if (exact && Number.isFinite(v)) {
159
+ s = ddAdd(s, [v, 0]);
160
+ out.push(s[0] + s[1]);
161
+ }
162
+ else {
163
+ exact = false;
164
+ out.push(Number.isNaN(v) || Number.isNaN(plain) ? NaN : plain);
165
+ }
166
+ }
167
+ return out;
168
+ }
169
+ /**
170
+ * Running products. Equivalent to R's `cumprod()`: products beyond the double range show as ±Infinity with the right
171
+ * sign, as R's long double accumulator does.
172
+ */
173
+ export function cumprod(x) {
174
+ const out = [];
175
+ // exact while the factors are finite and non-zero: double-double mantissa times 2^e
176
+ let p = [1, 0];
177
+ let e = 0;
178
+ let plain;
179
+ for (const v of Array.from(x)) {
180
+ if (plain === undefined && (!Number.isFinite(v) || v === 0))
181
+ plain = scaled(p, e);
182
+ if (plain !== undefined) {
183
+ plain *= v;
184
+ out.push(plain);
185
+ continue;
186
+ }
187
+ p = ddMul(p, [v, 0]);
188
+ const k = Math.floor(Math.log2(Math.abs(p[0])));
189
+ if (k > 500 || k < -500) {
190
+ p = [p[0] * 2 ** -k, p[1] * 2 ** -k];
191
+ e += k;
192
+ }
193
+ out.push(scaled(p, e));
194
+ }
195
+ return out;
196
+ }
197
+ /** (h + l) 2^e rounded to double (±Infinity or 0 beyond the range) */
198
+ function scaled(p, e) {
199
+ let r = p[0] + p[1];
200
+ while (e > 0 && Number.isFinite(r)) {
201
+ const s = Math.min(e, 1000);
202
+ r *= 2 ** s;
203
+ e -= s;
204
+ }
205
+ while (e < 0 && r !== 0) {
206
+ const s = Math.max(e, -1000);
207
+ r *= 2 ** s;
208
+ e -= s;
209
+ }
210
+ return r;
211
+ }
212
+ function cumExtreme(x, better) {
213
+ const out = [];
214
+ let m = NaN;
215
+ let seenNaN = false;
216
+ for (const v of Array.from(x)) {
217
+ if (seenNaN || Number.isNaN(v)) {
218
+ seenNaN = true;
219
+ out.push(NaN);
220
+ continue;
221
+ }
222
+ if (out.length === 0 || better(v, m))
223
+ m = v;
224
+ out.push(m);
225
+ }
226
+ return out;
227
+ }
228
+ /** Running maxima. Equivalent to R's `cummax()`: `NaN` from the first `NaN` on. */
229
+ export function cummax(x) {
230
+ return cumExtreme(x, (a, b) => a > b);
231
+ }
232
+ /** Running minima. Equivalent to R's `cummin()`. */
233
+ export function cummin(x) {
234
+ return cumExtreme(x, (a, b) => a < b);
235
+ }
236
+ /**
237
+ * Lagged and iterated differences. Equivalent to R's `diff()` for a vector (empty when `lag * differences` is at
238
+ * least the length).
239
+ */
240
+ export function diff(x, options = {}) {
241
+ const lag = options.lag ?? 1;
242
+ const differences = options.differences ?? 1;
243
+ if (!(Number.isInteger(lag) && lag >= 1 && Number.isInteger(differences) && differences >= 1)) {
244
+ throw new RangeError("'lag' and 'differences' must be integers >= 1");
245
+ }
246
+ let r = Array.from(x);
247
+ if (lag * differences >= r.length)
248
+ return [];
249
+ for (let d = 0; d < differences; d++) {
250
+ const next = [];
251
+ for (let i = lag; i < r.length; i++)
252
+ next.push(r[i] - r[i - lag]);
253
+ r = next;
254
+ }
255
+ return r;
256
+ }
@@ -0,0 +1,39 @@
1
+ import type { Sample } from "../htest/types.js";
2
+ /** Correlation or covariance method, as R's `method`. */
3
+ export type CorMethod = "pearson" | "kendall" | "spearman";
4
+ /** Handling of missing values, as R's `use`. */
5
+ export type CorUse = "everything" | "all.obs" | "complete.obs" | "na.or.complete" | "pairwise.complete.obs";
6
+ /** Options for {@link cov} and {@link cor}. */
7
+ export interface CovOptions {
8
+ /** Default `"pearson"`. Unambiguous abbreviations are accepted. */
9
+ method?: CorMethod | (string & {});
10
+ /** Default `"everything"`. Unambiguous abbreviations are accepted. */
11
+ use?: CorUse | (string & {});
12
+ }
13
+ type Input = Sample | readonly (readonly number[])[];
14
+ /**
15
+ * Covariance of two vectors, or covariance matrix of the columns of a matrix (or between the columns of `x` and `y`).
16
+ * Equivalent to R's `cov()`.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * cov([1, 2, 3, 4], [2, 4, 5, 9]); // 3.6666666666666665
21
+ * cov([[1, 2], [2, 4], [3, 5], [4, 9]]); // 2 x 2 matrix
22
+ * ```
23
+ */
24
+ export declare function cov(x: Sample, y: Sample, options?: CovOptions): number;
25
+ export declare function cov(x: Input, y?: Input, options?: CovOptions): number | number[][];
26
+ /**
27
+ * Correlation of two vectors, or correlation matrix of the columns of a matrix (or between the columns of `x` and
28
+ * `y`). Equivalent to R's `cor()`. Pearson correlations are computed in double-double, so they can be slightly more
29
+ * accurate than R's (exactly 1 for perfectly correlated data).
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * cor([1, 2, 3, 4], [2, 4, 5, 9]); // 0.9561828874675149
34
+ * cor([1, 2, 3, 4], [2, 4, 5, 9], { method: "spearman" }); // 1
35
+ * ```
36
+ */
37
+ export declare function cor(x: Sample, y: Sample, options?: CovOptions): number;
38
+ export declare function cor(x: Input, y?: Input, options?: CovOptions): number | number[][];
39
+ export {};
@@ -0,0 +1,105 @@
1
+ // Covariance and correlation of vectors and matrices: R's cov and cor with `method` and `use`.
2
+ //
3
+ // Written for rStats.js (no ported code). A matrix is an array of rows, its columns the variables. Pearson
4
+ // covariances and correlations are computed in double-double (src/internal/summary.ts, src/htest/cor.ts); Spearman's
5
+ // are Pearson's of the ranks (ranked after missing values are dropped as `use` says); Kendall's covariance is the
6
+ // sum of sign(x_i - x_j) sign(y_i - y_j) over all ordered pairs, as R reports it, and the correlation is tau-b.
7
+ // `use` follows R: "everything" (a missing value makes the entry NaN), "all.obs" (missing values are an error),
8
+ // "complete.obs" and "na.or.complete" (rows with any missing value are dropped) and "pairwise.complete.obs" (each
9
+ // pair of variables uses the rows where both are present).
10
+ import { kendall, pearsonDD } from "../htest/cor.js";
11
+ import { covariance } from "../internal/summary.js";
12
+ import { rank } from "./rank.js";
13
+ const METHODS = ["pearson", "kendall", "spearman"];
14
+ const USES = ["all.obs", "complete.obs", "pairwise.complete.obs", "everything", "na.or.complete"];
15
+ function match(v, all, dflt, what) {
16
+ if (v === undefined)
17
+ return dflt;
18
+ if (all.includes(v))
19
+ return v;
20
+ const hit = all.filter((a) => a.startsWith(v));
21
+ if (v.length === 0 || hit.length !== 1)
22
+ throw new RangeError(`invalid '${what}' argument`);
23
+ return hit[0];
24
+ }
25
+ function isMatrix(x) {
26
+ return x.length > 0 && Array.isArray(x[0]);
27
+ }
28
+ /** Columns of a matrix (array of rows), or the vector as one column */
29
+ function columns(x) {
30
+ if (!isMatrix(x))
31
+ return [Array.from(x)];
32
+ const ncol = x[0].length;
33
+ return Array.from({ length: ncol }, (_, j) => x.map((r) => r[j]));
34
+ }
35
+ function compute(x, y, options, correlation) {
36
+ const method = match(options.method, METHODS, "pearson", "method");
37
+ const use = match(options.use, USES, "everything", "use");
38
+ if (y === undefined && !isMatrix(x))
39
+ throw new TypeError("supply both 'x' and 'y' or a matrix-like 'x'");
40
+ const cx = columns(x);
41
+ const cy = y === undefined ? cx : columns(y);
42
+ const n = cx[0]?.length ?? 0;
43
+ if (cy.some((c) => c.length !== n))
44
+ throw new RangeError("incompatible dimensions");
45
+ const all = [...cx, ...cy];
46
+ if (use === "all.obs" && all.some((c) => c.some(Number.isNaN)))
47
+ throw new RangeError("missing observations in cov/cor");
48
+ if (!correlation && use === "pairwise.complete.obs" && method !== "pearson") {
49
+ throw new RangeError("cannot handle 'pairwise.complete.obs'");
50
+ }
51
+ let keepRows;
52
+ if (use === "complete.obs" || use === "na.or.complete") {
53
+ keepRows = Array.from({ length: n }, (_, i) => all.every((c) => !Number.isNaN(c[i])));
54
+ if (!keepRows.some(Boolean)) {
55
+ if (use === "complete.obs")
56
+ throw new RangeError("no complete element pairs");
57
+ return y === undefined || isMatrix(x) || isMatrix(y) ? cx.map(() => cy.map(() => NaN)) : NaN;
58
+ }
59
+ }
60
+ const prep = (c) => {
61
+ const v = keepRows === undefined ? c : c.filter((_, i) => keepRows[i]);
62
+ // ranks for Spearman, missing values kept in place (pairwise ranks are taken per pair below)
63
+ return method === "spearman" && use !== "pairwise.complete.obs" ? rank(v, { naLast: "keep" }) : v;
64
+ };
65
+ const px = cx.map(prep);
66
+ const py = y === undefined ? px : cy.map(prep);
67
+ const entry = (a, b) => {
68
+ let u = a;
69
+ let v = b;
70
+ if (use === "pairwise.complete.obs") {
71
+ const ok = a.map((t, i) => !Number.isNaN(t) && !Number.isNaN(b[i]));
72
+ u = a.filter((_, i) => ok[i]);
73
+ v = b.filter((_, i) => ok[i]);
74
+ if (method === "spearman") {
75
+ u = rank(u);
76
+ v = rank(v);
77
+ }
78
+ }
79
+ else if (u.some(Number.isNaN) || v.some(Number.isNaN))
80
+ return NaN;
81
+ if (method === "kendall") {
82
+ if (correlation)
83
+ return kendall(u, v).tau;
84
+ return 2 * kendall(u, v).s;
85
+ }
86
+ if (correlation)
87
+ return pearsonDD(u, v)[0];
88
+ return covariance(u, v);
89
+ };
90
+ 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
+ if (correlation && y === undefined && use !== "pairwise.complete.obs")
93
+ out.forEach((r, i) => (r[i] = 1));
94
+ return (y === undefined ? false : !isMatrix(x) && !isMatrix(y)) ? out[0][0] : out;
95
+ }
96
+ export function cov(x, y, options = {}) {
97
+ if (y !== undefined && !Array.isArray(y) && !ArrayBuffer.isView(y))
98
+ return compute(x, undefined, y, false);
99
+ return compute(x, y, options, false);
100
+ }
101
+ export function cor(x, y, options = {}) {
102
+ if (y !== undefined && !Array.isArray(y) && !ArrayBuffer.isView(y))
103
+ return compute(x, undefined, y, true);
104
+ return compute(x, y, options, true);
105
+ }
@@ -0,0 +1,64 @@
1
+ import type { Sample } from "../htest/types.js";
2
+ /** Options for {@link pretty}. */
3
+ export interface PrettyOptions {
4
+ /** Desired number of intervals. Default `5`. */
5
+ n?: number;
6
+ /** Minimal number of intervals. Default `n / 3` rounded down. */
7
+ minN?: number;
8
+ /** Factor applied to the cell when the range is very small. Default `0.75`. */
9
+ shrinkSml?: number;
10
+ /** Bias towards larger units. Default `1.5`. */
11
+ highUBias?: number;
12
+ /** Bias towards 5 over 2 times a power of 10. Default `0.5 + 1.5 * highUBias`. */
13
+ u5Bias?: number;
14
+ }
15
+ /**
16
+ * About n + 1 equally spaced "round" values (1, 2 or 5 times a power of 10) covering the range of `x`. Equivalent to
17
+ * R's `pretty()`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * pretty([0.3, 9.6]); // [0, 2, 4, 6, 8, 10]
22
+ * ```
23
+ */
24
+ export declare function pretty(x: Sample, options?: PrettyOptions): number[];
25
+ /** Options for {@link hist}. */
26
+ export interface HistOptions {
27
+ /**
28
+ * Break points, a number of cells (a suggestion for pretty), or a rule: `"Sturges"` (default), `"Scott"` or
29
+ * `"FD"` (Freedman-Diaconis).
30
+ */
31
+ breaks?: readonly number[] | number | "Sturges" | "Scott" | "FD" | "Freedman-Diaconis";
32
+ /** Cells closed on the right, (a, b] (default `true`). */
33
+ right?: boolean;
34
+ /** Close the first cell on the left (the last on the right when `right` is false). Default `true`. */
35
+ includeLowest?: boolean;
36
+ }
37
+ /** Result of {@link hist}. */
38
+ export interface HistResult {
39
+ breaks: number[];
40
+ counts: number[];
41
+ /** counts / (n * cell width) */
42
+ density: number[];
43
+ mids: number[];
44
+ }
45
+ /**
46
+ * Histogram counts. Equivalent to R's `hist(x, plot = FALSE)`: break points (by default pretty points over the range
47
+ * with about Sturges' number of cells), counts, densities and cell midpoints. Non-finite values are dropped.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * hist([1, 2, 2, 3, 3, 3, 4]).counts; // [3, 3, 1] for breaks [1, 2, 3, 4]
52
+ * ```
53
+ */
54
+ export declare function hist(x: Sample, options?: HistOptions): HistResult;
55
+ /**
56
+ * Empirical distribution function of `x`: a function returning the fraction of values at or below its argument.
57
+ * Equivalent to R's `ecdf()`. `NaN` values are dropped.
58
+ *
59
+ * @example
60
+ * ```ts
61
+ * ecdf([3, 1, 2])(2); // 2/3
62
+ * ```
63
+ */
64
+ export declare function ecdf(x: Sample): (q: number) => number;