1 | import mean from "./mean";
|
2 | import sampleVariance from "./sample_variance";
|
3 |
|
4 | /**
|
5 | * This is to compute [two sample t-test](http://en.wikipedia.org/wiki/Student's_t-test).
|
6 | * Tests whether "mean(X)-mean(Y) = difference", (
|
7 | * in the most common case, we often have `difference == 0` to test if two samples
|
8 | * are likely to be taken from populations with the same mean value) with
|
9 | * no prior knowledge on standard deviations of both samples
|
10 | * other than the fact that they have the same standard deviation.
|
11 | *
|
12 | * Usually the results here are used to look up a
|
13 | * [p-value](http://en.wikipedia.org/wiki/P-value), which, for
|
14 | * a certain level of significance, will let you determine that the
|
15 | * null hypothesis can or cannot be rejected.
|
16 | *
|
17 | * `diff` can be omitted if it equals 0.
|
18 | *
|
19 | * [This is used to confirm or deny](http://www.monarchlab.org/Lab/Research/Stats/2SampleT.aspx)
|
20 | * a null hypothesis that the two populations that have been sampled into
|
21 | * `sampleX` and `sampleY` are equal to each other.
|
22 | *
|
23 | * @param {Array<number>} sampleX a sample as an array of numbers
|
24 | * @param {Array<number>} sampleY a sample as an array of numbers
|
25 | * @param {number} [difference=0]
|
26 | * @returns {number|null} test result
|
27 | *
|
28 | * @example
|
29 | * tTestTwoSample([1, 2, 3, 4], [3, 4, 5, 6], 0); // => -2.1908902300206643
|
30 | */
|
31 | function tTestTwoSample(sampleX, sampleY, difference) {
|
32 | const n = sampleX.length;
|
33 | const m = sampleY.length;
|
34 |
|
35 | // If either sample doesn't actually have any values, we can't
|
36 | // compute this at all, so we return `null`.
|
37 | if (!n || !m) {
|
38 | return null;
|
39 | }
|
40 |
|
41 | // default difference (mu) is zero
|
42 | if (!difference) {
|
43 | difference = 0;
|
44 | }
|
45 |
|
46 | const meanX = mean(sampleX);
|
47 | const meanY = mean(sampleY);
|
48 | const sampleVarianceX = sampleVariance(sampleX);
|
49 | const sampleVarianceY = sampleVariance(sampleY);
|
50 |
|
51 | if (
|
52 | typeof meanX === "number" &&
|
53 | typeof meanY === "number" &&
|
54 | typeof sampleVarianceX === "number" &&
|
55 | typeof sampleVarianceY === "number"
|
56 | ) {
|
57 | const weightedVariance =
|
58 | ((n - 1) * sampleVarianceX + (m - 1) * sampleVarianceY) /
|
59 | (n + m - 2);
|
60 |
|
61 | return (
|
62 | (meanX - meanY - difference) /
|
63 | Math.sqrt(weightedVariance * (1 / n + 1 / m))
|
64 | );
|
65 | }
|
66 | }
|
67 |
|
68 | export default tTestTwoSample;
|