@numero-uno-jpn/rstats 1.8.0 → 1.10.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 (87) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.ja.md +7 -6
  3. package/README.md +6 -5
  4. package/dist/chunks/chunk-3QUOB47N.js +2 -0
  5. package/dist/chunks/{chunk-73IRLCTF.js → chunk-5PVS6TF2.js} +2 -2
  6. package/dist/chunks/chunk-6BDTLUNM.js +2 -0
  7. package/dist/chunks/{chunk-YD4U3QZ3.js → chunk-6U2ICRN3.js} +1 -1
  8. package/dist/chunks/chunk-6Y7OKIIM.js +2 -0
  9. package/dist/chunks/chunk-AQ7H4RJH.js +2 -0
  10. package/dist/chunks/{chunk-3DO726WZ.js → chunk-CN5D6ITZ.js} +2 -2
  11. package/dist/chunks/{chunk-V7ECXPWY.js → chunk-DC2FP6ZH.js} +2 -2
  12. package/dist/chunks/{chunk-IJST2ZGT.js → chunk-EDHAQHB7.js} +1 -1
  13. package/dist/chunks/chunk-F232C4SB.js +3 -0
  14. package/dist/chunks/{chunk-7ODUCEGX.js → chunk-F3WMBL5R.js} +2 -2
  15. package/dist/chunks/{chunk-QQHF5T2A.js → chunk-F5K2UXKW.js} +1 -1
  16. package/dist/chunks/{chunk-YT62DNDS.js → chunk-GYLFMAD6.js} +2 -2
  17. package/dist/chunks/{chunk-JXJDCQYE.js → chunk-IFFGJN5L.js} +2 -2
  18. package/dist/chunks/{chunk-TUL6UFLQ.js → chunk-ISNGTKVZ.js} +2 -2
  19. package/dist/chunks/chunk-JPQEOHZG.js +2 -0
  20. package/dist/chunks/{chunk-2ZQ2TSZS.js → chunk-JRMISESC.js} +2 -2
  21. package/dist/chunks/{chunk-LZB43TUL.js → chunk-K25FNCFH.js} +2 -2
  22. package/dist/chunks/{chunk-D3LKPD4H.js → chunk-KGDCQ2RV.js} +2 -2
  23. package/dist/chunks/{chunk-TYMC2D5I.js → chunk-LQWAHXHZ.js} +2 -2
  24. package/dist/chunks/{chunk-TQM6KGKT.js → chunk-MBQJWNPX.js} +2 -2
  25. package/dist/chunks/chunk-MULNGWZY.js +2 -0
  26. package/dist/chunks/{chunk-2X6PE6JF.js → chunk-MVIBJA2I.js} +2 -2
  27. package/dist/chunks/chunk-NAUAW5TO.js +2 -0
  28. package/dist/chunks/{chunk-RWZ6ICYN.js → chunk-NMVFSSEZ.js} +2 -2
  29. package/dist/chunks/{chunk-45HUI3M4.js → chunk-NNJGXB5K.js} +2 -2
  30. package/dist/chunks/{chunk-52RWDNO6.js → chunk-OQFZKQVT.js} +2 -2
  31. package/dist/chunks/chunk-OXYMJNVJ.js +2 -0
  32. package/dist/chunks/chunk-PJ73WRSA.js +2 -0
  33. package/dist/chunks/chunk-R5BXUEH3.js +2 -0
  34. package/dist/chunks/chunk-RPEFV4FR.js +2 -0
  35. package/dist/chunks/chunk-T3XFVWOW.js +2 -0
  36. package/dist/chunks/{chunk-GRTQ7FYQ.js → chunk-Y5M7NEJ5.js} +2 -2
  37. package/dist/chunks/chunk-Y7SXBQZY.js +2 -0
  38. package/dist/chunks/chunk-YCBQQHCB.js +2 -0
  39. package/dist/chunks/{chunk-JIAFWEED.js → chunk-YGKM6PIJ.js} +2 -2
  40. package/dist/chunks/{chunk-DG2RTNIR.js → chunk-ZUHBIFAJ.js} +2 -2
  41. package/dist/descriptive.js +2 -2
  42. package/dist/distributions.js +2 -2
  43. package/dist/entries/multivariate.d.ts +7 -0
  44. package/dist/entries/multivariate.js +8 -0
  45. package/dist/entries/tests.d.ts +3 -1
  46. package/dist/entries/tests.js +3 -1
  47. package/dist/htest/grubbs.d.ts +68 -0
  48. package/dist/htest/grubbs.js +151 -0
  49. package/dist/htest/multipleComparisons.d.ts +21 -0
  50. package/dist/htest/multipleComparisons.js +47 -0
  51. package/dist/htest/rankTests.d.ts +35 -0
  52. package/dist/htest/rankTests.js +89 -1
  53. package/dist/internal/summary.js +8 -2
  54. package/dist/linalg/symmetricLeading.d.ts +8 -0
  55. package/dist/linalg/symmetricLeading.js +231 -0
  56. package/dist/linalg.js +2 -2
  57. package/dist/mixed.js +2 -2
  58. package/dist/multivariate/cancor.d.ts +55 -0
  59. package/dist/multivariate/cancor.js +167 -0
  60. package/dist/multivariate/cmdscale.d.ts +40 -0
  61. package/dist/multivariate/cmdscale.js +171 -0
  62. package/dist/multivariate/dist.d.ts +63 -0
  63. package/dist/multivariate/dist.js +218 -0
  64. package/dist/multivariate/hclust.d.ts +58 -0
  65. package/dist/multivariate/hclust.js +264 -0
  66. package/dist/multivariate/kmeans.d.ts +58 -0
  67. package/dist/multivariate/kmeans.js +392 -0
  68. package/dist/multivariate/lda.d.ts +146 -0
  69. package/dist/multivariate/lda.js +325 -0
  70. package/dist/multivariate/manova.d.ts +106 -0
  71. package/dist/multivariate/manova.js +303 -0
  72. package/dist/multivariate.js +2 -0
  73. package/dist/numerics.js +2 -2
  74. package/dist/regression.js +2 -2
  75. package/dist/rstats.js +16 -16
  76. package/dist/special.js +2 -2
  77. package/dist/tests.js +15 -15
  78. package/llms.txt +4 -1
  79. package/package.json +6 -1
  80. package/dist/chunks/chunk-53OM63EU.js +0 -2
  81. package/dist/chunks/chunk-ANZUXEMH.js +0 -3
  82. package/dist/chunks/chunk-BHQGMZTI.js +0 -2
  83. package/dist/chunks/chunk-HXYH5ZMB.js +0 -2
  84. package/dist/chunks/chunk-HYJ4MIZE.js +0 -2
  85. package/dist/chunks/chunk-MLNWWGGE.js +0 -2
  86. package/dist/chunks/chunk-VB6PVRSN.js +0 -2
  87. package/dist/chunks/chunk-Y4KNH43T.js +0 -2
@@ -0,0 +1,7 @@
1
+ export { manova, manovaSummary, type ManovaFit, type ManovaOptions, type ManovaSummary, type ManovaSummaryOptions, type ManovaTestName, type MatrixTable } from "../multivariate/manova.js";
2
+ export { cancor, type CancorOptions, type CancorResult } from "../multivariate/cancor.js";
3
+ export { lda, ldaPredict, type LdaOptions, type LdaPredictionOptions, type LdaFit, type LdaPrediction, type LdaCVResult, type LdaTable } from "../multivariate/lda.js";
4
+ export { dist, asDist, type DistMethod, type DistResult, type DistOptions, type AsDistOptions } from "../multivariate/dist.js";
5
+ export { hclust, cutree, type HclustMethod, type HclustFit, type HclustOptions, type CutreeOptions, type CutreeResult } from "../multivariate/hclust.js";
6
+ export { kmeans, type KmeansFit, type KmeansOptions, type KmeansTable, type KmeansInputTable } from "../multivariate/kmeans.js";
7
+ export { cmdscale, type CmdscaleOptions, type CmdscaleResult, type CmdscaleInputTable } from "../multivariate/cmdscale.js";
@@ -0,0 +1,8 @@
1
+ // Multivariate analysis (rStats.js/multivariate).
2
+ export { manova, manovaSummary } from "../multivariate/manova.js";
3
+ export { cancor } from "../multivariate/cancor.js";
4
+ export { lda, ldaPredict } from "../multivariate/lda.js";
5
+ export { dist, asDist } from "../multivariate/dist.js";
6
+ export { hclust, cutree } from "../multivariate/hclust.js";
7
+ export { kmeans } from "../multivariate/kmeans.js";
8
+ export { cmdscale } from "../multivariate/cmdscale.js";
@@ -16,7 +16,7 @@ export { boschlooTest, type BoschlooTestOptions, type BoschlooTestResult, type B
16
16
  export { gTest, stuartMaxwellTest, goodmanKruskalGamma, lblTest, type GTestCorrection, type GTestOptions, type GTestResult, type StuartMaxwellTestResult, type GoodmanKruskalGammaOptions, type GoodmanKruskalGammaResult, type LblTestOptions, type LblTestResult, } from "../htest/tableTests.js";
17
17
  export { mcnemarTest, type McnemarTestOptions, type McnemarTestResult } from "../htest/mcnemarTest.js";
18
18
  export { varTest, bartlettTest, type VarTestOptions, type VarTestResult, type BartlettTestResult } from "../htest/varTest.js";
19
- export { kruskalTest, friedmanTest, cochranQTest, quadeTest, flignerTest, moodTest, type ChisqStatTestResult, type QuadeTestResult, type MoodTestOptions, } from "../htest/rankTests.js";
19
+ export { kruskalTest, friedmanTest, cochranQTest, quadeTest, flignerTest, moodTest, pageTest, type ChisqStatTestResult, type QuadeTestResult, type MoodTestOptions, type PageTestOptions, } from "../htest/rankTests.js";
20
20
  export { onewayTest, shapiroTest, type OnewayTestOptions, type OnewayTestResult } from "../htest/onewayTest.js";
21
21
  export { mantelhaenTest, type MantelhaenTestOptions, type MantelhaenTestResult } from "../htest/mantelhaenTest.js";
22
22
  export { ansariTest, type AnsariTestOptions } from "../htest/ansariTest.js";
@@ -67,3 +67,5 @@ export { cuminc, timepoints, crr, predictCrr, type CumincCurve, type CumincTest,
67
67
  export { survreg, survregPredict, survregResiduals, type SurvregDistribution, type SurvregType, type SurvregControl, type SurvregOptions, type SurvregResult, type SurvregPredictOptions, type SurvregPredictionResult, type SurvregResidualsOptions } from "../models/survreg.js";
68
68
  export { epiSsequb, epiSsequc, epiSsninfb, epiSsninfc, epiSssupb, epiSssupc, powerPaired2x2, ssizeCT, powerCT, ssizeEpi, powerEpi, numDEpi, ph2simon, type EpiOptions, type EpiResult, type PowerPaired2x2Options, type PowerPaired2x2Result, type SurvivalOptions, type SSizeCTResult, type SimonRow, type SimonDesign, type SimonDesignResult, } from "../htest/sampleSize.js";
69
69
  export { escalc, rma, confintRma, predictRma, regtest, type EscalcMeasure, type EscalcOptions, type EscalcResult, type MetaMethod, type MetaTest, type RmaControl, type RmaOptions, type RmaResult, type ConfintRmaOptions, type PredictRmaOptions, type RegtestOptions, type ModeratorMatrix, type NumericMatrix, } from "../models/metaAnalysis.js";
70
+ export { tamhaneT2Test, type TamhaneT2Options } from "../htest/multipleComparisons.js";
71
+ export { grubbsTest, pgrubbs, qgrubbs, type GrubbsTestOptions, type GrubbsTestResult } from "../htest/grubbs.js";
@@ -16,7 +16,7 @@ export { boschlooTest, } from "../htest/boschlooTest.js";
16
16
  export { gTest, stuartMaxwellTest, goodmanKruskalGamma, lblTest, } from "../htest/tableTests.js";
17
17
  export { mcnemarTest } from "../htest/mcnemarTest.js";
18
18
  export { varTest, bartlettTest } from "../htest/varTest.js";
19
- export { kruskalTest, friedmanTest, cochranQTest, quadeTest, flignerTest, moodTest, } from "../htest/rankTests.js";
19
+ export { kruskalTest, friedmanTest, cochranQTest, quadeTest, flignerTest, moodTest, pageTest, } from "../htest/rankTests.js";
20
20
  export { onewayTest, shapiroTest } from "../htest/onewayTest.js";
21
21
  export { mantelhaenTest } from "../htest/mantelhaenTest.js";
22
22
  export { ansariTest } from "../htest/ansariTest.js";
@@ -62,3 +62,5 @@ export { cuminc, timepoints, crr, predictCrr, } from "../models/competingRisks.j
62
62
  export { survreg, survregPredict, survregResiduals } from "../models/survreg.js";
63
63
  export { epiSsequb, epiSsequc, epiSsninfb, epiSsninfc, epiSssupb, epiSssupc, powerPaired2x2, ssizeCT, powerCT, ssizeEpi, powerEpi, numDEpi, ph2simon, } from "../htest/sampleSize.js";
64
64
  export { escalc, rma, confintRma, predictRma, regtest, } from "../models/metaAnalysis.js";
65
+ export { tamhaneT2Test } from "../htest/multipleComparisons.js";
66
+ export { grubbsTest, pgrubbs, qgrubbs } from "../htest/grubbs.js";
@@ -0,0 +1,68 @@
1
+ import { type Vectorizable, type VectorResult } from "../internal/vectorize.js";
2
+ import type { Sample } from "./types.js";
3
+ /**
4
+ * Options for {@link grubbsTest}.
5
+ *
6
+ * @category Hypothesis tests
7
+ */
8
+ export interface GrubbsTestOptions {
9
+ /** Grubbs test type. Only 10 is supported in 1.9.0. Default 10. */
10
+ type?: 10 | 11 | 20;
11
+ /** Test the lowest rather than the highest observation. Default false. */
12
+ opposite?: boolean;
13
+ /** Use a two-sided p-value. Default false. */
14
+ twoSided?: boolean;
15
+ }
16
+ /**
17
+ * Result of Grubbs' test for one outlier.
18
+ *
19
+ * @category Hypothesis tests
20
+ */
21
+ export interface GrubbsTestResult {
22
+ /** Description of the test (R's `method`). */
23
+ method: string;
24
+ /** Grubbs G and U statistics, in that order. */
25
+ statistic: [number, number];
26
+ /** Names corresponding to the two entries of `statistic`. */
27
+ statisticName: ["G", "U"];
28
+ /** P-value for the selected tail and sidedness. */
29
+ pValue: number;
30
+ /** Text description of the alternative hypothesis. */
31
+ alternative: string;
32
+ /** Warnings produced while evaluating the test. */
33
+ warnings: string[];
34
+ }
35
+ /**
36
+ * Cumulative distribution of the type-10 Grubbs statistic. Vectorised over q.
37
+ * Equivalent to R's `outliers::pgrubbs()`. Type 10 only.
38
+ *
39
+ * @param q Statistic value(s).
40
+ * @param n Sample size.
41
+ * @param type Only 10 is supported; 11 and 20 are intentionally deferred.
42
+ *
43
+ * @category Distributions
44
+ */
45
+ export declare function pgrubbs<T extends Vectorizable>(q: T, n: number, type?: number): VectorResult<T>;
46
+ /**
47
+ * Quantile of the type-10 Grubbs statistic. Vectorised over p.
48
+ * Equivalent to R's `outliers::qgrubbs()`. Type 10 only.
49
+ *
50
+ * @param p Probability value(s).
51
+ * @param n Sample size.
52
+ * @param type Only 10 is supported; 11 and 20 are intentionally deferred.
53
+ *
54
+ * @category Distributions
55
+ */
56
+ export declare function qgrubbs<T extends Vectorizable>(p: T, n: number, type?: number): VectorResult<T>;
57
+ /**
58
+ * Grubbs' test for one outlier. Type 10 selects the highest or lowest observation and reports G and U.
59
+ * NaN observations are omitted; infinities are rejected. A constant sample has undefined statistics and p = NaN.
60
+ *
61
+ * Equivalent to R's `outliers::grubbs.test()`. Type 10 only.
62
+ *
63
+ * @param x Numeric sample.
64
+ * @param options Type, tail and sidedness.
65
+ *
66
+ * @category Hypothesis tests
67
+ */
68
+ export declare function grubbsTest(x: Sample, options?: GrubbsTestOptions): GrubbsTestResult;
@@ -0,0 +1,151 @@
1
+ // Grubbs' single-outlier test, type 10 (Grubbs 1950; Pearson & Sekar 1936).
2
+ // Implemented from the published statistic and the independently checked Pearson–Sekar transform;
3
+ // no package implementation or R source is used.
4
+ import { groupMoments, standardize } from "../internal/summary.js";
5
+ import { vectorize } from "../internal/vectorize.js";
6
+ import { betaIncDD } from "../special/incbet.js";
7
+ import { ddDiv, ddMulNum, ddSub, twoProd } from "../special/dd.js";
8
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
9
+ import { checkOptions } from "../internal/checkOptions.js";
10
+ const GRUBBS_TEST_KEYS = ["type", "opposite", "twoSided"];
11
+ /** Upper tail probability of the type-10 Grubbs statistic. */
12
+ function grubbsTail10(q, n) {
13
+ if (Number.isNaN(q) || Number.isNaN(n))
14
+ return NaN;
15
+ if (!Number.isSafeInteger(n) || n < 3)
16
+ return NaN;
17
+ if (q <= 0)
18
+ return 1;
19
+ if (q >= (n - 1) / Math.sqrt(n))
20
+ return 0;
21
+ const n1 = n - 1;
22
+ const n1sq = twoProd(n1, n1);
23
+ const nq2 = ddMulNum(twoProd(q, q), n);
24
+ const den = ddSub(n1sq, nq2);
25
+ if (den[0] + den[1] <= 0)
26
+ return 0;
27
+ // Algebraically, (n - 2)/(n - 2 + t^2) = ((n - 1)^2 - n q^2)/(n - 1)^2.
28
+ // Form this beta argument directly: deriving it through t^2 loses relative precision near the upper boundary.
29
+ const x = ddDiv(den, n1sq);
30
+ const xc = ddDiv(nq2, n1sq);
31
+ const lower = betaIncDD((n - 2) / 2, 0.5, x, xc, true, false);
32
+ return Math.min(1, (n * lower) / 2);
33
+ }
34
+ /** Pearson–Sekar CDF of the type-10 Grubbs statistic. */
35
+ function pgrubbs10(q, n) {
36
+ const tail = grubbsTail10(q, n);
37
+ return Number.isNaN(tail) ? NaN : 1 - tail;
38
+ }
39
+ /**
40
+ * Cumulative distribution of the type-10 Grubbs statistic. Vectorised over q.
41
+ * Equivalent to R's `outliers::pgrubbs()`. Type 10 only.
42
+ *
43
+ * @param q Statistic value(s).
44
+ * @param n Sample size.
45
+ * @param type Only 10 is supported; 11 and 20 are intentionally deferred.
46
+ *
47
+ * @category Distributions
48
+ */
49
+ export function pgrubbs(q, n, type = 10) {
50
+ if (type !== 10)
51
+ throw new RangeError(`Grubbs type ${type} is not supported in rStats.js 1.9.0 (type 10 only)`);
52
+ return vectorize(q, (v) => pgrubbs10(v, n));
53
+ }
54
+ /** Invert the monotone type-10 CDF by bisection on the bounded Grubbs statistic. */
55
+ function qgrubbsLowerBound(n) {
56
+ let lo = 0, hi = (n - 1) / Math.sqrt(n);
57
+ for (let i = 0; i < 80; i++) {
58
+ const mid = lo + (hi - lo) / 2;
59
+ if (mid === lo || mid === hi)
60
+ break;
61
+ if (grubbsTail10(mid, n) >= 1)
62
+ lo = mid;
63
+ else
64
+ hi = mid;
65
+ }
66
+ return hi;
67
+ }
68
+ function qgrubbs10(p, n) {
69
+ if (Number.isNaN(p) || Number.isNaN(n))
70
+ return NaN;
71
+ if (!Number.isSafeInteger(n) || n < 3 || p < 0 || p > 1)
72
+ return NaN;
73
+ if (p === 0)
74
+ return qgrubbsLowerBound(n);
75
+ if (p === 1)
76
+ return (n - 1) / Math.sqrt(n);
77
+ let lo = 0;
78
+ let hi = (n - 1) / Math.sqrt(n);
79
+ for (let i = 0; i < 80; i++) {
80
+ const mid = lo + (hi - lo) / 2;
81
+ if (pgrubbs10(mid, n) < p)
82
+ lo = mid;
83
+ else
84
+ hi = mid;
85
+ }
86
+ return lo + (hi - lo) / 2;
87
+ }
88
+ /**
89
+ * Quantile of the type-10 Grubbs statistic. Vectorised over p.
90
+ * Equivalent to R's `outliers::qgrubbs()`. Type 10 only.
91
+ *
92
+ * @param p Probability value(s).
93
+ * @param n Sample size.
94
+ * @param type Only 10 is supported; 11 and 20 are intentionally deferred.
95
+ *
96
+ * @category Distributions
97
+ */
98
+ export function qgrubbs(p, n, type = 10) {
99
+ if (type !== 10)
100
+ throw new RangeError(`Grubbs type ${type} is not supported in rStats.js 1.9.0 (type 10 only)`);
101
+ return vectorize(p, (v) => qgrubbs10(v, n));
102
+ }
103
+ /**
104
+ * Grubbs' test for one outlier. Type 10 selects the highest or lowest observation and reports G and U.
105
+ * NaN observations are omitted; infinities are rejected. A constant sample has undefined statistics and p = NaN.
106
+ *
107
+ * Equivalent to R's `outliers::grubbs.test()`. Type 10 only.
108
+ *
109
+ * @param x Numeric sample.
110
+ * @param options Type, tail and sidedness.
111
+ *
112
+ * @category Hypothesis tests
113
+ */
114
+ export function grubbsTest(x, options = {}) {
115
+ checkOptions(options, GRUBBS_TEST_KEYS, "grubbsTest"); // generated: option-keys.mjs
116
+ const type = options.type ?? 10;
117
+ if (type !== 10)
118
+ throw new RangeError(`Grubbs type ${type} is not supported in rStats.js 1.9.0 (type 10 only)`);
119
+ const values = Array.from(x).filter((v) => !Number.isNaN(v));
120
+ if (values.some((v) => !Number.isFinite(v)))
121
+ throw new RangeError("x must contain finite values");
122
+ const n = values.length;
123
+ if (n < 2)
124
+ throw new RangeError("sample size must be at least 2");
125
+ const opposite = options.opposite ?? false;
126
+ const twoSided = options.twoSided ?? false;
127
+ let extreme = values[0];
128
+ for (let i = 1; i < values.length; i++) {
129
+ if (opposite ? values[i] < extreme : values[i] > extreme)
130
+ extreme = values[i];
131
+ }
132
+ const z = standardize(values);
133
+ const index = values.indexOf(extreme);
134
+ const G = Math.abs(z[index]);
135
+ const rest = values.slice();
136
+ rest.splice(index, 1);
137
+ const moments = groupMoments([values, rest]);
138
+ const U = ((n - 2) * moments.variance[1]) / ((n - 1) * moments.variance[0]);
139
+ const tail = grubbsTail10(G, n);
140
+ const cdf = 1 - tail;
141
+ const pValue = Number.isNaN(G) ? NaN : Math.min(1, twoSided ? 2 * Math.min(cdf, tail) : tail);
142
+ const direction = opposite ? "lowest" : "highest";
143
+ return {
144
+ method: "Grubbs test for one outlier",
145
+ statistic: [G, U],
146
+ statisticName: ["G", "U"],
147
+ pValue,
148
+ alternative: `${direction} value ${String(extreme)} is an outlier`,
149
+ warnings: n === 2 ? ["NaNs produced"] : [],
150
+ };
151
+ }
@@ -146,6 +146,27 @@ export declare function manyOneUTest(x: Sample, g: readonly GroupLabel[], option
146
146
  * @category Multiple comparisons
147
147
  */
148
148
  export declare function dscfAllPairsTest(x: Sample, g: readonly GroupLabel[]): PMCMRResult;
149
+ /**
150
+ * Options of Tamhane's T2 and T2' all-pairs tests.
151
+ *
152
+ * @category Multiple comparisons
153
+ */
154
+ export interface TamhaneT2Options {
155
+ /** Use Welch–Satterthwaite degrees of freedom (T2); false uses n_i + n_j − 2 (T2'). Default true. */
156
+ welch?: boolean;
157
+ }
158
+ /**
159
+ * Tamhane's T2 (Welch–Satterthwaite df) or T2' (pooled df) all-pairs test of means. Equivalent to
160
+ * `PMCMRplus::tamhaneT2Test()` in R. Character and numeric group labels are ordered as R's factor() levels; list input
161
+ * uses the one-based list positions as group labels.
162
+ *
163
+ * @param x Observations, or a list of samples (one per group).
164
+ * @param g Group labels parallel to x; omit for a list of samples.
165
+ * @param options Set `welch: false` for T2'.
166
+ *
167
+ * @category Multiple comparisons
168
+ */
169
+ export declare function tamhaneT2Test(x: Sample | readonly Sample[], g?: readonly GroupLabel[], options?: TamhaneT2Options): PMCMRResult;
149
170
  /**
150
171
  * Games-Howell all-pairs test of means with Welch's standard errors and degrees of freedom. Equivalent to
151
172
  * `PMCMRplus::gamesHowellTest()` in R.
@@ -16,6 +16,7 @@
16
16
  // - Tukey (1953), Tukey-Kramer: the pooled standard error, studentized range on N - k degrees of freedom.
17
17
  import { pnorm } from "../distributions/normal.js";
18
18
  import { ptukey } from "../distributions/tukey.js";
19
+ import { pt } from "../distributions/t.js";
19
20
  import { groupMoments, ldexp, rank, satterthwaiteDfPM, tieCounts } from "../internal/summary.js";
20
21
  import { pDunnettUpper } from "./dunnett.js";
21
22
  import { labelledGroups } from "./groups.js";
@@ -31,6 +32,7 @@ const DUNNETT_TEST_KEYS = ["alternative"];
31
32
  const MANY_ONE_UTEST_KEYS = ["pAdjustMethod", "alternative"];
32
33
  const DUNN_TEST_KEYS = ["method", "altp"];
33
34
  const GLHT_DUNNETT_KEYS = ["alternative"];
35
+ const TAMHANE_T2_TEST_KEYS = ["welch"];
34
36
  const TIES_WARNING = "Ties are present. z-quantiles were corrected for ties.";
35
37
  function layout(x, g) {
36
38
  const { labels, groups } = labelledGroups(x, g);
@@ -309,6 +311,51 @@ export function dscfAllPairsTest(x, g) {
309
311
  const p = stat.map((row) => row.map((q) => (Number.isNaN(q) ? NaN : upperRange(q, d.k, Infinity))));
310
312
  return reported("dscfAllPairsTest", allPairs(d, "Dwass-Steele-Critchlow-Fligner all-pairs test", stat, p, "single-step"));
311
313
  }
314
+ /**
315
+ * Tamhane's T2 (Welch–Satterthwaite df) or T2' (pooled df) all-pairs test of means. Equivalent to
316
+ * `PMCMRplus::tamhaneT2Test()` in R. Character and numeric group labels are ordered as R's factor() levels; list input
317
+ * uses the one-based list positions as group labels.
318
+ *
319
+ * @param x Observations, or a list of samples (one per group).
320
+ * @param g Group labels parallel to x; omit for a list of samples.
321
+ * @param options Set `welch: false` for T2'.
322
+ *
323
+ * @category Multiple comparisons
324
+ */
325
+ export function tamhaneT2Test(x, g, options = {}) {
326
+ checkOptions(options, TAMHANE_T2_TEST_KEYS, "tamhaneT2Test"); // generated: option-keys.mjs
327
+ const d = (() => {
328
+ if (g !== undefined)
329
+ return layout(x, g);
330
+ const grouped = labelledGroups(x);
331
+ const k = grouped.groups.length;
332
+ if (k < 2)
333
+ throw new RangeError("there must be at least two groups");
334
+ const n = grouped.groups.map((s) => s.length);
335
+ return { labels: grouped.labels, groups: grouped.groups, n, N: n.reduce((a, b) => a + b, 0), k };
336
+ })();
337
+ // Work in the common power-of-two-scaled coordinates. groupMoments exposes its scaled groups so the
338
+ // variances stay finite even when the original data are around 1e100 (the T2 choice avoids R's overflow artifact).
339
+ const scaled = groupMoments(d.groups);
340
+ const gm = groupMoments(scaled.groups);
341
+ const welch = options.welch ?? true;
342
+ const m = d.k * (d.k - 1) / 2;
343
+ const statistic = lowerTable(d.k, (i, j) => {
344
+ const se2 = gm.variance[i] / d.n[i] + gm.variance[j] / d.n[j];
345
+ return (gm.mean[i] - gm.mean[j]) / Math.sqrt(se2);
346
+ });
347
+ const pValue = lowerTable(d.k, (i, j) => {
348
+ const t = statistic[i - 1][j];
349
+ if (Number.isNaN(t))
350
+ return NaN;
351
+ const df = welch
352
+ ? satterthwaiteDfPM([gm.variance[i], gm.variance[j]], [d.n[i], d.n[j]])
353
+ : d.n[i] + d.n[j] - 2;
354
+ const raw = 2 * pt(Math.abs(t), df, { lowerTail: false });
355
+ return raw >= 1 ? 1 : -Math.expm1(m * Math.log1p(-raw));
356
+ });
357
+ return reported("tamhaneT2Test", allPairs(d, welch ? "Tamhane's T2-test for unequal variances" : "Tamhane's T2'-test for unequal variances", statistic, pValue, welch ? "T2 (Sidak)" : "T2' (Sidak)"));
358
+ }
312
359
  /**
313
360
  * Games-Howell all-pairs test of means with Welch's standard errors and degrees of freedom. Equivalent to
314
361
  * `PMCMRplus::gamesHowellTest()` in R.
@@ -66,6 +66,41 @@ export declare function friedmanTest(y: readonly (readonly number[])[]): ChisqSt
66
66
  * @param data The data frame: an object of columns (`null` or `NaN` for a missing value).
67
67
  */
68
68
  export declare function friedmanTest(formula: string, data: DataFrame): ChisqStatTestResult;
69
+ /**
70
+ * Options for {@link pageTest}.
71
+ *
72
+ * @category Hypothesis tests
73
+ */
74
+ export interface PageTestOptions {
75
+ /** Alternative hypothesis. Abbreviations are accepted. Default "two.sided". */
76
+ alternative?: Alternative | "two" | "l" | "g";
77
+ }
78
+ /**
79
+ * Page's ordered aligned rank-sum test. Equivalent to R's `PMCMRplus::pageTest()`.
80
+ *
81
+ * @param y A blocks-by-treatments matrix in the hypothesised treatment order.
82
+ * @param options Alternative hypothesis.
83
+ *
84
+ * @category Hypothesis tests
85
+ */
86
+ export declare function pageTest(y: readonly (readonly number[])[], options?: PageTestOptions): HTest;
87
+ /**
88
+ * Page's test from long-form observations. Treatment and block labels follow R's factor() level order.
89
+ *
90
+ * @param x Numeric observations.
91
+ * @param groups Treatment labels, parallel to x.
92
+ * @param blocks Block labels, parallel to x.
93
+ * @param options Alternative hypothesis.
94
+ */
95
+ export declare function pageTest(x: Sample, groups: readonly GroupLabel[], blocks: readonly GroupLabel[], options?: PageTestOptions): HTest;
96
+ /**
97
+ * Page's test from a formula and data frame: `"y ~ treatment | block"`.
98
+ *
99
+ * @param formula Formula with one treatment and one block variable.
100
+ * @param data Data frame.
101
+ * @param options Alternative hypothesis.
102
+ */
103
+ export declare function pageTest(formula: string, data: DataFrame, options?: PageTestOptions): HTest;
69
104
  /**
70
105
  * Cochran's Q test for binary responses in an unreplicated complete block design. Equivalent to
71
106
  * `DescTools::CochranQTest()` in R. Takes a matrix: the Friedman test of the 0/1 matrix (with ties), reported as Q.
@@ -20,13 +20,15 @@ import { pf1 } from "../distributions/f.js";
20
20
  import { pgamma1 } from "../distributions/gamma.js";
21
21
  import { pnorm, qnorm } from "../distributions/normal.js";
22
22
  import { rank, scaleToUnit, tieCounts, variance } from "../internal/summary.js";
23
- import { completeRows, median, toGroups } from "./groups.js";
23
+ import { completeRows, median, toGroups, factorLabels, compareLabels } from "./groups.js";
24
24
  import { blockData, kSampleData, twoGroupData } from "./testFormula.js";
25
25
  import { matchAlternative } from "./types.js";
26
26
  import { maxOf, minOf } from "../internal/extremes.js";
27
27
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
28
28
  import { checkOptions } from "../internal/checkOptions.js";
29
+ import { isOptionsObject } from "../internal/optionalArgs.js";
29
30
  const MOOD_TEST_KEYS = ["alternative"];
31
+ const PAGE_TEST_KEYS = ["alternative"];
30
32
  function chisqResult(method, name, statistic, df) {
31
33
  return {
32
34
  method,
@@ -91,6 +93,92 @@ export function friedmanTest(y, data) {
91
93
  const stat = (12 * ss) / (n * k * (k + 1) - ties / (k - 1));
92
94
  return chisqResult("Friedman rank sum test", "Friedman chi-squared", stat, k - 1);
93
95
  }
96
+ export function pageTest(y, groupsOrOptions = {}, blocks, maybeOptions = {}) {
97
+ if (typeof y !== "string" && isOptionsObject(groupsOrOptions))
98
+ checkOptions(groupsOrOptions, PAGE_TEST_KEYS, "pageTest"); // generated: option-keys.mjs
99
+ if (isOptionsObject(blocks))
100
+ checkOptions(blocks, PAGE_TEST_KEYS, "pageTest"); // generated: option-keys.mjs
101
+ checkOptions(maybeOptions, PAGE_TEST_KEYS, "pageTest"); // generated: option-keys.mjs
102
+ let matrix;
103
+ let options;
104
+ if (typeof y === "string") {
105
+ matrix = blockData(y, groupsOrOptions);
106
+ options = blocks ?? {};
107
+ }
108
+ else if (Array.isArray(blocks)) {
109
+ const x = Array.from(y);
110
+ const groups = groupsOrOptions;
111
+ const blockLabelsInput = blocks;
112
+ if (x.length !== groups.length || x.length !== blockLabelsInput.length) {
113
+ throw new RangeError("'x', 'groups' and 'blocks' must have the same length");
114
+ }
115
+ if (!x.every(Number.isFinite))
116
+ throw new RangeError("missing or non-finite values are not allowed");
117
+ const treatmentLabels = factorLabels(groups);
118
+ const blockLabels = factorLabels(blockLabelsInput);
119
+ if (treatmentLabels.some((v) => typeof v === "number" && Number.isNaN(v)) ||
120
+ blockLabels.some((v) => typeof v === "number" && Number.isNaN(v))) {
121
+ throw new RangeError("missing treatment or block labels are not allowed");
122
+ }
123
+ const ts = Array.from(new Set(treatmentLabels)).sort(compareLabels);
124
+ const bs = Array.from(new Set(blockLabels)).sort(compareLabels);
125
+ if (ts.length < 2 || bs.length < 1)
126
+ throw new RangeError("at least two treatments and one block are required");
127
+ const ti = new Map(ts.map((v, i) => [v, i]));
128
+ const bi = new Map(bs.map((v, i) => [v, i]));
129
+ matrix = bs.map(() => new Array(ts.length).fill(NaN));
130
+ for (let i = 0; i < x.length; i++) {
131
+ const r = bi.get(blockLabels[i]);
132
+ const col = ti.get(treatmentLabels[i]);
133
+ if (!Number.isNaN(matrix[r][col]))
134
+ throw new RangeError("not an unreplicated complete block design");
135
+ matrix[r][col] = x[i];
136
+ }
137
+ if (matrix.some((row) => row.some((v) => Number.isNaN(v)))) {
138
+ throw new RangeError("not an unreplicated complete block design");
139
+ }
140
+ options = maybeOptions;
141
+ }
142
+ else {
143
+ matrix = y.map((row) => Array.from(row));
144
+ options = groupsOrOptions;
145
+ }
146
+ const n = matrix.length;
147
+ const k = matrix[0]?.length ?? 0;
148
+ if (n < 1 || k < 2 || matrix.some((row) => row.length !== k)) {
149
+ throw new RangeError("'y' must be a non-empty matrix with at least two columns");
150
+ }
151
+ if (matrix.some((row) => row.some((v) => !Number.isFinite(v)))) {
152
+ throw new RangeError("missing or non-finite values are not allowed in a block");
153
+ }
154
+ const alternative = matchAlternative(options.alternative);
155
+ const sums = new Array(k).fill(0);
156
+ for (const row of matrix) {
157
+ const ranks = rank(row);
158
+ for (let j = 0; j < k; j++)
159
+ sums[j] += ranks[j];
160
+ }
161
+ let estimate = 0;
162
+ for (let j = 0; j < k; j++)
163
+ estimate += (j + 1) * sums[j];
164
+ const expected = n * k * (k + 1) ** 2 / 4;
165
+ const v = n * k ** 2 * (k - 1) * (k + 1) ** 2 / 144;
166
+ const statistic = (estimate - expected - 0.5) / Math.sqrt(v);
167
+ const pValue = alternative === "less"
168
+ ? pnorm(statistic)
169
+ : alternative === "greater"
170
+ ? pnorm(statistic, { lowerTail: false })
171
+ : 2 * pnorm(-Math.abs(statistic));
172
+ return {
173
+ method: "Page's ordered aligned rank sum test",
174
+ alternative,
175
+ statistic,
176
+ statisticName: "z",
177
+ pValue,
178
+ estimate,
179
+ warnings: [],
180
+ };
181
+ }
94
182
  /**
95
183
  * Cochran's Q test for binary responses in an unreplicated complete block design. Equivalent to
96
184
  * `DescTools::CochranQTest()` in R. Takes a matrix: the Friedman test of the 0/1 matrix (with ties), reported as Q.
@@ -253,8 +253,14 @@ export function standardize(x) {
253
253
  const c = x.length < 2 ? undefined : centered(x);
254
254
  if (c === undefined)
255
255
  return x.map(() => NaN);
256
- const sd = Math.sqrt(ddDivNum(crossSum(c.d, c.d), x.length - 1)[0]);
257
- return c.d.map((v) => (sd > 0 ? v[0] / sd : NaN));
256
+ const variance = ddDivNum(crossSum(c.d, c.d), x.length - 1);
257
+ const sd = Math.sqrt(variance[0] + variance[1]);
258
+ return c.d.map((v) => {
259
+ if (!(sd > 0))
260
+ return NaN;
261
+ const z = ddDivNum(v, sd);
262
+ return z[0] + z[1];
263
+ });
258
264
  }
259
265
  export function groupMoments(groups) {
260
266
  const { groups: scaled, k } = scaleToUnit(groups);
@@ -0,0 +1,8 @@
1
+ export interface SymmetricLeading {
2
+ /** All n eigenvalues, decreasing. */
3
+ values: number[];
4
+ /** The first k eigenvectors (unit length), vectors[j] for values[j]. */
5
+ vectors: number[][];
6
+ }
7
+ /** a: the matrix as rows (only the lower triangle is read); k: how many leading eigenvectors */
8
+ export declare function symmetricLeading(a: readonly (readonly number[])[], k: number): SymmetricLeading;