Statistics

Correlations: deciding which relations deserve to be read

A correlation matrix can give hundreds of mathematically correct numbers and several false conclusions. Computing a correlation is not our problem; deciding which test to read, and whether the relation deserves to be read at all, is. This article follows our correlation and test engines step by step, in the order they run, with the rules that decide and the measurements that show where the usual shortcuts go wrong: what one observation is, which quantity is compared and which test it calls for, which assumptions are checked and on what, what time, controls and segments change, how many tests were really run, and what the engines refuse to compute rather than guess.

Correct numbers, false conclusions

Every coefficient of a correlation matrix can be computed exactly and still mislead. Among twenty variables with no link to an outcome, one will look related by chance; five rows of the same customer count as five customers; two series that both trend look linked; groups that differ in spread look different in mean; a third variable drives two others; a relation holds in every segment and reverses in the total. None of these is a calculation error. Each is a reading error, and a matrix of hundreds of numbers multiplies the occasions to make one.

So the work of our engines is not to compute a correlation, which takes one line, but to decide, for each relation, which test to read, whether the relation deserves to be read, and to say why when it does not. They run the same sequence every time:

  1. What is one observation? Independent units, paired measures or repeated units.
  2. What kind of variables? The pair of types sets the family of tests.
  3. Which quantity is compared, and which assumptions hold? Means, distributions or proportions first; then the assumptions, checked on the object the test actually uses. Our engine’s rule for choosing is an implementation choice, stated with its limits.
  4. Is time manufacturing the relation? When a time column is declared, trending series are not tested on their levels.
  5. Are extreme values creating or hiding it? The engines clean nothing themselves: extreme values are to be analysed beforehand, and their influence is reported.
  6. Does it survive the controls and the segments? Common causes and Simpson reversals.
  7. How many tests were really run? One family per question, adjusted before any filter.
  8. How large is it, and what was not tested? Named effect sizes, and every refusal recorded with its reason.

Several steps rest on what the analyst declares: the identifier of a customer, the time column, the controls, the segments. The engines apply the structure they are given; they do not guess it. The numbers below were measured by running our engines on simulated data where the truth is known; each simulation states its domain, because a level that holds on one grid of situations says nothing about another.

Step 1: what is one observation?

A test counts its observations as independent unless it is told otherwise, so the structure of the data decides which test is right before any number is computed. Three structures are kept apart. Independent units: different customers, different policies. Paired measures: the same people before and after, whose two columns are not independent. Repeated units: one customer on five rows, five policies, five months or five claims, rows that share everything specific to that customer.

We simulated 40 customers with 5 rows each and a binary characteristic of the customer with no relation to the outcome. Counting every row as independent, the test declared a relation in 32.5% of 200 simulations, instead of 5%. When the customer identifier is declared, our test engine makes the customer the observation: its rows are summarised into one, the average of its numeric values and its most frequent category, and the false relations fell to 5%. Without a declared identifier, every row counts as a unit and the result says so, so that the reader knows which assumption the p-value rests on. Paired data are declared too, and each subject is then compared with itself (step 3). Our correlation engine has no customer identifier: outside its time mode it counts rows as independent, so data with several rows per customer go through the test engine, or are summarised first.

No relation, customers repeated over several rows: false relations declared, rows against customers as observations
No relation, customers repeated over several rows: false relations declared, rows against customers as observations

Step 2: the variables choose the family of tests

The type of each variable is declared, not inferred from the way it is stored; only the target is classified by the engine from its values: when it is left undeclared, or when it is declared as a category but is numeric with more than ten distinct values, in which case it is treated as continuous. The pair of types then sets the question, and the question sets the family of tests:

  • Two continuous measures: a correlation, linear or by ranks.
  • A category against a continuous measure: a comparison of groups, never a correlation computed on category codes.
  • Two categories: a contingency table.
  • An outcome of 0 or 1 measured twice or more on the same subjects: a test of paired proportions.

There is no ordinal type. A bonus class or an age band is declared either as a category, and its order is ignored, or as a number, and its steps are taken as equal. That choice is the analyst’s, and it changes the test.

Step 3: the quantity compared first, then the assumptions

The first question is not which assumptions hold but what is compared, because each test answers its own question. The quantity comes first, then the structure of the data, then the assumptions:

  • Means, an average claim cost for instance: Student’s t or the ANOVA, and often preferably Welch’s versions, which do not assume equal variances, at a small cost in power when the variances are equal (measured below). Exact normality of the values is not always required: with enough values per group, the mean is close to normal by the central limit theorem, and what weighs more is the independence of the rows, very unequal spreads and heavy tails.
  • Distributions, or ranks, whether the values of one group tend to be larger than those of another: Mann-Whitney for two groups, Kruskal-Wallis for more. Mann-Whitney is a stochastic comparison, through the probability that a value of one group exceeds a value of the other, ties counted half; it reads as a test of medians only under the assumption that the two distributions differ by a shift, and it is never a test of means.
  • Proportions, a claim rate or a share of customers: a contingency table, chi-square when the expected counts allow it, an exact test otherwise.
  • The structure then sets the version: the same subjects measured twice or more call for paired tests (see the annex), several rows of one customer for the unit of independence of step 1, dated series for step 4.

Only then come the assumptions of the chosen test. Our test engine implements this with a rule of its own, an implementation choice and not a universal law: for a continuous measure it is not told which quantity the analyst wants, and it lets pre-tests of normality and of variance choose between the tests of means and the rank tests. Its limits are stated and measured below: a failed normality pre-test changes the question, from means to the stochastic comparison, and Welch’s tests run on every case held the level better in the situations we simulated. A parametric test is right only if its assumptions hold, and the assumption is not always about the raw values. Our test engine checks normality on the object the test actually uses: the values of each group when the groups are independent; the differences between the two measures of each subject when the data are paired; the residuals left once the subject and the level are removed when the same subjects are measured three times or more. Equality of variances is checked with Levene’s test centred on the median, which an extreme value moves less than the mean. These pre-tests have their own declared levels, 5% as shipped, set apart from the level of the tests reported. The engine then switches to one test, never runs both, and writes which assumption failed. For three groups or more the rule reads: every group normal and equal variances, the classical ANOVA; every group normal and unequal variances, Welch’s ANOVA; otherwise Kruskal-Wallis. Welch’s ANOVA is therefore not the default: it is read only when the variance pre-test rejects, and two groups follow the same rule with Student’s t, Welch’s t and Mann-Whitney. The full list, case by case, is in the annex at the end.

Welch’s ANOVA is the switch that matters most when groups differ in spread. It weights each group by the precision of its mean instead of pooling the variances. With k groups, ni values, mean y¯i and sample variance si2 in group i:

wi=nisi2,y¯w=∑i=1kwiy¯i∑i=1kwi,F*=1k−1∑i=1kwi(y¯i−y¯w)21+2(k−2)k2−1Λ
(1)
Λ=∑i=1k(1−wi/W)2ni−1,W=∑i=1kwi,ν1=k−1,ν2=k2−13Λ
(2)

and F* is read on a Fisher distribution with ν1 and ν2 degrees of freedom. A small, dispersed group gets a small weight and costs degrees of freedom; the classical ANOVA instead gives its large variance to every group through the pooled variance. With two groups, F* is the square of Welch’s t.

We measured what that changes by running our engine on three normal groups with the same mean, sizes 10, 30 and 30, the group of 10 having a standard deviation between 1 and 4 and the two others 1, with 2,000 simulations per point. At a ratio of 4, the classical ANOVA declared a difference in 24.95% of cases instead of 5%; Kruskal-Wallis in 11.15%, because it tests whether the distributions are the same, not only the means; Welch’s ANOVA in 4.3%; the whole procedure of our engine, pre-tests included, in 5.75%. A second simulation of the same situation, with other seeds, gave 27.9%, 13.05%, 6.35% and 7.5%: the order holds, the levels move by up to three points. The pre-tests have a cost, and we state it. At ratios of 1.5 and 2, the variance pre-test often misses a moderate difference in spread, the classical ANOVA is chosen, and the procedure rose to 8.65% and 9.15% (between 8.4% and 9.3% on a separate bench of 4,000 simulations per situation, with two and three groups). And since every group goes through a normality test, with three normal groups at least one fails it by chance in about one case in seven; the rank test is then read, and under unequal spreads and sizes the procedure stays near 7% (between 6.9% and 7.6% on the same bench). Against the usual practice of reading the classical ANOVA, the procedure is far safer; against Welch’s ANOVA run on every case, without pre-tests, it is not: on this grid Welch’s ANOVA alone stayed between 4.3% and 5.5% at every ratio. When the dispersed group is the large one (sizes 30, 30 and 10), the classical ANOVA errs the other way: 2.85% at a ratio of 4, a test that has become timid and loses power, while the procedure stayed between 5.05% and 6%.

Contingency tables have their own trap. The chi-square is an approximation that needs enough expected counts Eij=ni·n·j/n, where ni· and n·j are the totals of row i and column j and n the grand total. Our engine applies Cochran’s rule: no expected count below 1 and at most one in five below 5. When the rule fails, it replaces the chi-square by an exact test whose p-value is estimated by drawing tables with the same margins (formula (20) in the technical details). On five shapes of sparse tables with rows and columns independent, about 2,000 tables per shape, the chi-square rejected between 0.57% and 6.06% of them: too often on one shape, almost never on another, an error whose direction cannot be known in advance. Our engine stayed between 1.77% and 4.82% (in the simulation each exact p-value was estimated from 2,000 tables; the shipped setting draws 20,000). On a large table where the rule holds, both rejected 5%. An exact test run on every table, without Cochran’s rule, did as well (between 1.54% and 4.75%): the gain is over the chi-square read without checking its expected counts.

Two consequences are stated rather than hidden. The test is chosen by a pre-test on the same data, so what we measure above is the false-alarm rate of the whole two-step procedure, not that of each test alone. And on large samples a normality test rejects tiny departures, so the rank-based path becomes the rule; the engine does not invoke the central limit theorem to keep a parametric test, although for a comparison of means on many values it would often justify Welch’s t. An analyst whose question is about means should say so and read a test of means, not the rank test the rule chose.

Three normal groups with equal means, the smallest one more dispersed: false differences declared by the classical ANOVA, Kruskal-Wallis, Welch’s ANOVA and our engine
Three normal groups with equal means, the smallest one more dispersed: false differences declared by the classical ANOVA, Kruskal-Wallis, Welch’s ANOVA and our engine
Sparse independent tables declared dependent: chi-square against our engine
Sparse independent tables declared dependent: chi-square against our engine

Step 3, continued: comparing groups, and what each test computes

Comparing a continuous measure across groups, the cost of a claim by region or by channel for instance, is the most frequent question of a study, and the one where the choice of test weighs most. Every block of our test engine applies the same rule, the implementation choice described in step 3, at the declared levels of its pre-tests:

  • Every group passes the normality pre-test, and Levene’s test does not reject equal variances: Student’s t for two groups, the classical ANOVA for three or more.
  • Every group is normal, but the variances differ: Welch’s t for two groups, Welch’s ANOVA for three or more.
  • At least one group is not normal: Mann-Whitney for two groups, Kruskal-Wallis for three or more.

When the continuous measure is the outcome and the category the explanatory variable, two groups follow the version written for three or more, which comes to the same for the t tests, and asymptotically for the rank test: the ANOVA F of two groups is the square of Student’s t, Welch’s F the square of Welch’s t, and Kruskal-Wallis is then the large-sample form of Mann-Whitney. For two groups of sizes n1 and n2, means y¯1 and y¯2 and sample variances s12 and s22, Student’s t pools the two variances into one, sp2:

t=y¯1−y¯2sp1/n1+1/n2,sp2=(n1−1)s12+(n2−1)s22n1+n2−2,ν=n1+n2−2
(3)

Welch’s t keeps each variance with its own group, and pays for it with degrees of freedom estimated from the data, those of Welch and Satterthwaite:

tW=y¯1−y¯2v1+v2,νW=(v1+v2)2v12/(n1−1)+v22/(n2−1),vi=si2/ni
(4)

Both are read on a Student distribution with ν or νW degrees of freedom, and the p-value is two-sided: p=2P(Tν>|t|). νW lies between the smaller of n1−1 and n2−1 and n1+n2−2: a small group with a large variance brings it close to its own size, and the test becomes more cautious exactly where Student’s t would be overconfident.

The rank tests replace the values by their ranks among all the values of the groups compared, a tie receiving the mean of the ranks it occupies. With R1 the sum of the ranks of group 1:

U1=R1−n1(n1+1)2,rrb=1−2U1n1n2
(5)

U1 counts the pairs, one value from each group, in which the value of group 1 is the larger, a tie counting one half; the rank-biserial correlation rrb, the effect size of the test, is the share of pairs in which group 2 is larger minus the share in which group 1 is larger, between −1 and 1. For k groups, with Ri the sum of the ranks of group i, n the total number of values and τj the size of the j-th set of tied values, Kruskal-Wallis computes

H=12Cn(n+1)∑i=1kRi2ni−3(n+1)C,C=1−∑j(τj3−τj)n3−n
(6)

read on a chi-square distribution with k−1 degrees of freedom; C corrects for ties. Neither rank test compares means, nor in general medians. Mann-Whitney is a stochastic comparison: with X1 a value drawn from group 1 and X2 a value drawn from group 2, it tests whether θ=P(X1>X2)+12P(X1=X2), the probability that the first exceeds the second, ties counted half, estimated by U1/(n1n2), differs from one half; Kruskal-Wallis extends the question to k groups. Software does not all report the same U: some give U1, others the statistic of the other group, U2=n1n2−U1, or the smaller of the two, so the orientation is read before the effect. A probability of superiority of one half does not mean equal distributions: two distributions symmetric around the same centre but of different spreads give exactly one half, and the test is not built to tell them apart; whether two whole distributions are equal is another question, for other tests, Kolmogorov-Smirnov among them. It reads as a difference of medians only under the assumption of a pure shift, distributions of the same shape that differ only in location, and its level is exact only when the groups have the same distribution: with unequal spreads it can reject at equal means, as measured in what the engines do not claim. The p-value of Mann-Whitney is computed exactly or by its normal approximation, corrected for ties and for continuity, as the numerical library decides from the sizes and the ties.

Every check made before a test

Normality and equal variances are the checks everyone knows. They are only two of those our engines run before a p-value is read, and each check that fails changes the test, or turns the test into a refusal with its reason. In the order they run:

  • The unit of independence. In our test engine, with a declared identifier, one row per customer, policy or subject (step 1); without it, every row counts as a unit and the result says so.
  • The pairing. Paired data keep only the subjects observed at every level; a subject missing one measurement is left out, never compared with someone else.
  • The types. Declared by the analyst; the outcome alone is classified by the engine (step 2).
  • Enough data. A category with fewer than 3 values is left out of the test, of its pre-tests, of its effect size and of its pairwise comparisons, and named with its count; with fewer than two categories left, or fewer than three complete rows, the variable is reported not tested; below eight rows, a correlation is computed on ranks.
  • Normality, on the object the test uses (step 3): Shapiro-Wilk up to 5,000 values, D’Agostino-Pearson beyond, where the approximation of Shapiro-Wilk is no longer valid; a group of fewer than three values, or constant, counts as not normal.
  • Equal variances: Levene’s test centred on the median between groups; before a linear correlation, Breusch-Pagan’s test on the residuals of the regression of one variable on the other, which checks that their spread does not change along the line.
  • The expected counts of a contingency table: Cochran’s rule before any chi-square (step 3).
  • The controls: a control observed on too few of the pair’s rows, or constant, is set aside and named (step 6); a row with a missing control is left out and counted.
  • Time, when a time column is declared (step 4): no two rows of a series at the same date, finite values, a unit-root test and a stationarity test on each segment, differences where needed, prewhitening, then a check that the innovations no longer depend on their past, on at least 50 dates per segment.
  • Influence: for each pair, our correlation engine reports the weight of the most influential point on the fit, against its usual threshold (formula (18)). It is a diagnostic: it changes no test, and no point is removed automatically.
  • Impossible values and outliers, analysed before the tests (step 5).

What the engines do not check is said too. There is no generic layer of business rules: an age of 190, or a five-year-old recorded as a smoker, is found by the domain checks the analyst declares with the business, or by our outlier detector when the value is extreme against the others, not by the tests. Normality and variance are tested on the same data as the test they choose; what that two-step procedure costs is measured in step 3.

Step 4: time, with a time column, never the levels

Two series that both trend over time look correlated whatever their link, a trap known since Yule in 1926 as nonsense correlation. We ran our correlation engine on 200 pairs of independent random walks of 200 dates, each the running sum of independent standard normal steps. Read as independent rows, their levels had a typical correlation of 0.43 in absolute value, and a relation was declared in 85.5% of the pairs.

When a time column is declared, our correlation engine does not test the levels. Each series is first examined by two tests, one that looks for a unit root and one that tests stationarity, and it is differenced unless both find it stationary; inside declared segments, never across their boundary. Its own dynamics are then removed by an autoregressive model whose order is chosen by the Akaike criterion on that series alone, never by looking at the correlation it will be tested for: this is prewhitening. What remains, the innovations, is what is new at each date. If the innovations are still dependent over time, the pair is declared not computable instead of tested; otherwise the test runs on them, with a standard error that does not assume equal variances and degrees of freedom corrected for small samples. The correlation of the levels is still shown, labelled as descriptive only. On the same pairs, the typical correlation of the innovations was 0.05 and a relation was declared in 3% of them; no pair was refused. The procedure had been validated beforehand on a grid of 90 simulated situations, with at least 50 dates per series: the share of false relations stayed at or below 6.6% in each of them, and we claim nothing beyond that grid.

Written out, a segment of a series is kept in levels only when the unit-root test rejects and the stationarity test does not, pADF<αu and pKPSS≥αu, with αu = 5% as shipped; every other outcome is differenced. The order a^ of the autoregressive model of a segment of n values is the one that minimises the Akaike criterion, every candidate being compared on the same n−A dates, and the innovations that remain go through the whiteness test of Ljung and Box:

a^=argmin0≤a≤A(n−A)lnσ^a2+2(a+1),A=min(⌊10log10n⌋, ⌊(n−1)/3⌋)
(7)
Q=nε(nε+2)∑ℓ=1ℓmaxρ^ℓ2nε−ℓ,ℓmax=min(10, ⌊nε/5⌋)
(8)

where σ^a2 is the mean square of the residuals of the model of order a, nε the number of innovations of the segment and ρ^ℓ their autocorrelation at lag ℓ. Q is read on a chi-square distribution with ℓmax degrees of freedom, and the pair is tested only if every series tested passes at the level of 1% divided by the number of series checked, a Bonferroni correction; otherwise it is reported not computable, with that reason.

Looking for the period in which two variables move together is tempting, and dangerous: among all the windows of a series, the best one shows a strong correlation even when there is no link, the winner’s curse. Our engine can search for that window, but the result is exploratory only. With n rows and a minimum length L, the shipped one being the larger of 5 and 30% of n, there are m=K(K+1)/2 windows with K=n−L+1, and the p-value of the selected window is multiplied by m (capped at 1). By default the search starts only when the correlation over the declared period reaches 0.6 in absolute value; to measure the curse, we switched it on for 200 pairs of unrelated series of 200 points, independent standard normal draws, that is 10,011 windows of at least 60 points each. The best window had an average absolute correlation of 0.26, against 0.055 on the declared period; read as if it had been chosen in advance, it was “significant” in 54.5% of the pairs; after the adjustment, in none. That adjustment, the p-value multiplied by the number of windows, makes the window an honest exploration, not a confirmation: a window that passes it still has to be tested on other data. The window never promotes, filters or ranks a relation: every main statistic stays computed on the declared period, where 6.5% of these pairs were declared related, within the simulation error of 5%. A window generates a hypothesis, to be tested on other data; it is never evidence. For the same reason, the engine offers no scan for the lag at which two series are the most correlated: such a search needs its own protocol: in our time-series protocol, the Granger test searches lags 1 to 7 and pays for that search, corrected over the lags and over the two directions.

The window rule, in symbols, with rI and pI the correlation of a window I of at least L consecutive rows and its p-value:

I^=argmaxI:|I|≥L|rI|,pI^adj=min(1, mpI^),m=K(K+1)2,K=n−L+1
(9)

Comparing periods fixed in advance is the honest way to look for the period in which a relation holds. When a column gives each row its period, for instance before and after a dated change of tariff, of process or of regime, declared by the analyst or found by the break tests of our time-series protocol, our correlation engine computes the correlation inside each period and over all of them together, in one family of tests, and compares their signs (step 6). The periods are chosen before looking at the correlations, so nothing is selected on the result. The engine does not cut the periods itself, and a relation that holds in one period only is reported as such, with the size of that period.

Independent random walks: correlation of the levels against correlation of the innovations, computed by our engine
Independent random walks: correlation of the levels against correlation of the innovations, computed by our engine
Unrelated series: the best window declared significant, read naively or adjusted for the windows tried, against the declared period
Unrelated series: the best window declared significant, read naively or adjusted for the windows tried, against the declared period

Step 5: extreme values, analysed upstream

A single extreme point can create a correlation, two unrelated clouds and one point far out on the diagonal, or hide one, a point on the wrong side. Our correlation and test engines do not call our outlier detector: finding impossible values and anomalies is a recommended step before the tests, not an automatic step of the engines. It is done by the domain checks the analyst declares with the business and by our outlier detector, and decided on before the tests run. A period is set aside only for a documented reason, independent of the result hoped for. It can change everything: in our SGTech engagement, a variable that should move with CH4 flow showed a correlation of −7% before cleaning, and +71% once the corrupted periods had been isolated.

The detector follows the order described in that article: on a series, it first finds its regimes, the periods within which values are comparable; on a column of amounts, it first checks whether the column mixes several populations, as our article on multimodal columns shows; then, inside each regime or each population, it flags values with robust measures, medians and quantiles rather than mean and standard deviation. Nothing is deleted: each flag is coded and reviewed, and only the values found to be errors are corrected or set aside before the tests.

By default, the engines change no value themselves; in our test engine, capping or removing extreme values is an option the analyst must switch on, applied once to all the data before the tests: each continuous variable is capped at its 1st and 99th percentiles as shipped, or its values beyond 1.5 interquartile ranges from the quartiles are set to missing. For each pair, our correlation engine reports how much the most influential point weighs on the fit, the rank correlation next to the linear one, and a p-value computed by permutation, so that a relation carried by a few points shows; it never excludes a point automatically.

Step 6: controls and segments

Two variables can be strongly correlated only because a third one drives both. We simulated two variables, each made of a common factor plus its own noise, with no direct link between them: their correlation was 0.73 on average. Once the factor was declared as a control, the partial correlation was −0.004 on average, and the test declared a link in 3% of the simulations, as expected when there is none. The partial correlation removes the controls Z (with a constant) from each of the two variables by regression, then tests the correlation of the two residuals ex and ey:

rxy·Z=corr(ex,ey),t=rxy·Zn−2−c1−rxy·Z2
(10)

where n is the number of rows where the two variables and every control are present and c the number of linearly independent control columns (a categorical control with G levels counts G−1); t is read on a Student distribution with n−2−c degrees of freedom. Each control costs one degree of freedom; a test on n−2 would forget it and declare too many relations. The same count sets the width of the confidence interval of a partial correlation, through n−3−c instead of n−3. A row with a missing control is left out and counted, never filled in silently. Outside the time mode, a control that cannot be used on its own, observed on fewer than five of the pair’s rows or constant where it is observed, is set aside and named with its reason, and the partial correlation is computed exactly as if that column had never been given: it removes no row. When no declared control can be used, there is no partial correlation; the relation is judged on the simple correlation, and the result says so rather than presenting it as a partial one.

A correlation computed on all rows together can also have the opposite sign of the correlation inside every segment. We simulated three segments of 150 rows. Inside each one, the outcome falls when the variable rises; but the segments with high values of the variable are also those with high outcomes. Over 100 simulated data sets, the correlation was −0.81 on average inside the segments and 0.92 on all rows together. When segments are declared, our correlation engine computes the correlation in each segment and on all rows, and compares the signs. The segments that count are those whose correlation is significant after an adjustment of their own and that have at least 50 observations; their majority sign is weighted by their sizes. If the correlation on all rows is significant and of the opposite sign, the result carries a reversal flag that names the segments. On the simulated data sets the reversal was flagged in 100% of cases. The paradox itself is discussed in our article on statistical paradoxes.

Two correlations that mislead: a reversal across segments and a common factor
Two correlations that mislead: a reversal across segments and a common factor

Step 7: how many tests were really run

A study rarely tests one pair. It crosses twenty variables with an outcome, then does it again by region or by product, and each test has a 5% chance of a false alarm. We simulated 20 variables with no relation at all to the outcome, 200 rows each, 200 times. Keeping every correlation whose own p-value fell below 5% gave at least one “relation” in 62.5% of the studies. Adjusting all the tests of the question together, with the Benjamini–Hochberg method, brought it down to 3%.

The adjustment is computed within a family. If the family holds m tests whose p-values, sorted in increasing order, are p(1)≤…≤p(m), the adjusted value of the i-th is

q(i)=minj≥imin(1,mp(j)j)(11)

and a relation is retained only when its adjusted value is below the declared level α; this keeps the expected share of false discoveries among the relations retained at or below α when the tests are independent or positively dependent. Everything therefore depends on m, that is on what the family contains. In our engines a family is one question, such as “which variables are related to the outcome?”, and it holds every variable or pair tested for that question, not only the pairs that look interesting; in our correlation engine, the pairs of every segment and of all rows together form one family. The adjustment comes before any filter on the size of the effect; a common shortcut keeps the large coefficients first and corrects only those, which shrinks m below the search that was really done. Only a finite p-value between 0 and 1 is a test: a statistic that cannot be defined stays out of the family, so that it neither dilutes the others nor counts as a test (step 8). The families of each analysis are listed with their size. When an analysis is run segment by segment, each segment is its own family, and the result says that discoveries are controlled within each segment, not across them.

Comparisons between categories follow the same discipline. The pairwise comparisons of a test of three groups or more are issued only when that test is significant after adjustment, and they form their own family. A category is named as “the one that stands out” only when a pairwise comparison is significant after its own adjustment; otherwise none is named, and the result says why. The rankings of categories by their mean, which our test engine also gives, describe the sample and are labelled as such: they test no pair, and a difference between two categories is read only in an adjusted pairwise comparison.

Studies of variables unrelated to the outcome that report at least one relation: raw p-values against the adjustment over the whole family
Studies of variables unrelated to the outcome that report at least one relation: raw p-values against the adjustment over the whole family

Step 8: the size, by its real name, and what was not tested

A p-value says whether an effect could be zero, not how large it is. Each test result carries an effect size and the name of its index: Hedges’ g for two means, the mean paired difference over its standard deviation for a paired t, the rank-biserial correlation for Mann-Whitney and Wilcoxon, eta squared and omega squared for an ANOVA, the rank epsilon squared and its bias-corrected version for Kruskal-Wallis, Kendall’s coefficient of concordance for Friedman, Cramér’s V for a table, the odds ratio for a 2 × 2 table, the difference of the two proportions for McNemar, Bonett’s d for each pair after Welch’s ANOVA, Cohen’s f² for an effect measured with controls. Indices that share a name in textbooks are not interchangeable, and a number without its name cannot be compared with anything. Omega squared corrects eta squared for its optimism; it assumes equal variances, so after Welch’s ANOVA it is given as indicative. An index that two of our outputs used to print under the name epsilon squared for Kruskal-Wallis is not a published index; both now give the rank epsilon squared, the share of the variance of the ranks explained by the groups, on the same scale as eta squared.

Confidence intervals are given where they are computed: for linear correlations, for odds ratios and for the differences of the pairwise comparisons. For the other effect sizes the interval is not computed yet, and the report says so rather than citing one. A correlation that is not significant is written with its interval, never as “no relation”: the data do not exclude correlations up to the largest bound of that interval. Power computed at the observed effect is only a re-expression of the p-value; it is given as information, never used to explain a result that is not significant.

What was not tested is a result too. Every variable, pair, category or control left out is a line of a report, with one of four statuses, not tested, category excluded (the test ran without that category), control excluded (the test ran without that control, on the rows it would have had without it) or not computed (a derived quantity, such as the sample size needed for a given power, could not be computed), and with its reason in figures: fewer than three complete rows, a single level, no variance, a category below the declared minimum count, a control observed on too few rows or constant, no variation within any subject, a statistic that cannot be defined, a model that cannot be estimated. We ran our test engine on 122 simulated rows with five continuous variables, one of them related to the outcome, plus a constant column, a column observed on two rows only, and a category of two rows. Nothing stopped: the report listed 47 lines, each with its reason, for instance a zero variance, where no correlation is defined, or two complete rows, where a correlation test needs at least three. The family of the question “which continuous variables are related to the outcome?” held 5 tests, as it does when the two unusable columns are removed, and the adjusted p-value of the related variable was identical in both runs. In the analysis that adds every other variable as a control, the column observed on two rows was set aside from the controls of each of the six models, with its reason, and the six models came out exactly as when the column is absent: same rows, same p-values before and after adjustment. Our tests check this in general: a control that cannot be used changes nothing in a test that does not need it.

In time mode, a pair is refused when two rows of a series share a date, when values are infinite, when no segment has at least 50 dates, when the innovations are degenerate, or when they are still dependent. A refused pair stays in the table with its reason, outside the family of tests, so that its absence cannot be read as an absence of relation, and no size filter hides it. An error while computing a pair is recorded with the step that failed, and the analysis continues with the others.

The size of an effect, and what it changes in our decisions

A p-value mixes two things, the size of an effect and the number of rows that measured it. With enough rows, a negligible difference becomes significant; with too few, a large one does not. Our test engine therefore reads both, and the size decides what is listed as a finding. For two means the size is Cohen’s d on the pooled standard deviation of formula (3), corrected for small samples by Hedges’ factor J:

d=y¯1−y¯2sp,g=Jd,J=1−34(n1+n2−2)−1
(12)

Here d is positive when group 1 has the larger mean, whereas rrb of formula (5) is positive when the values of group 2 tend to be larger: the two signs follow opposite orders of the groups. Some outputs of our test engine, and the pairwise comparisons, also take the difference the other way round, group 2 minus group 1. A sign is therefore read with the order of the groups printed next to it, and the words that describe an effect read only its absolute value, |d| or |rrb|.

For k groups of n values in total, with y¯ the overall mean and SST the sum of the squared deviations of all the values from y¯, the ANOVA reports the share of the variance explained by the groups, η2, and its less optimistic estimate for the population, ω2, which can fall below zero:

η2=SSBSST,ω2=SSB−(k−1)MSWSST+MSW,SSB=∑i=1kni(y¯i−y¯)2,MSW=SST−SSBn−k
(13)

and Kruskal-Wallis, from its statistic H of formula (6), the same share computed on the ranks, εR2, and its version adjusted for what chance alone would give, ηH2:

εR2=Hn−1,ηH2=H−k+1n−k
(14)

The size acts directly on what our test engine reports. A categorical variable is listed among those related to the outcome only when its p-value, adjusted over its family, is below the declared level and the share it explains, η2 or εR2, reaches 0.1; a correlation with the outcome is listed only when its coefficient reaches 0.2 in absolute value. These minimum sizes, 0.1 and 0.2, are decision choices of our engine, written in its code and stated here, not universal constants: whether an effect is large enough to list depends on the number of tests made, on the uncertainty of the effect measured, which on few rows can be far from its true value, and on the objective of the study, and another study may justify other values. They filter the list of findings, never the family of tests, which holds every test made (step 7). Each size also carries a word, very small, small, medium or large, from the conventional cuts of Cohen (1988), 0.01, 0.06 and 0.14 for a share of variance, 0.2, 0.5 and 0.8 for d, 0.1, 0.3 and 0.5 for a correlation; the words describe, they decide nothing.

The two panels below show why both are needed. On the left, three groups of 2,000 values whose means differ by a tenth of a standard deviation: the ANOVA gives p < 0.001, and the share explained is 0.005, very small; the engine does not list the variable. Over 2,000 simulated data sets of that kind, the test was significant in 92.5% of them, the share explained stayed between 0.001 and 0.004 in eight cases out of ten, and the variable was listed in none. On the right, three groups of 8 values whose means differ by 0.8 standard deviation, a large difference: p = 0.24, not significant, for a share explained of 0.126. Over 2,000 data sets of that kind, the test was significant in 32.5% of them only, and the share explained, whose value in the population is 0.125, came out at 0.19 in the median data set: with few values, η2 overstates the effect, which is why ω2 is given next to it (0.041 on the data set shown). On a hundred data sets of each kind, the whole engine, run end to end, listed exactly the variables this rule predicts.

What this changes: a large sample is not a reason to report every significant difference, and a small sample is not a proof that there is none. A difference that matters to the business, a gap of price or of claim cost, is judged on its size, and on its interval where one is computed; the p-value only says whether chance alone could have produced it.

Box plots of two simulated data sets read by our test engine: a tiny difference on many values, significant and not listed; a large difference on few values, not significant
Box plots of two simulated data sets read by our test engine: a tiny difference on many values, significant and not listed; a large difference on few values, not significant

Power: the risk α, and the risk β

A test makes two kinds of error. It can declare an effect that does not exist, with a probability α fixed in advance, 5% as shipped; every adjustment of this article protects that risk. It can also miss an effect that does exist, with a probability β that depends on the size of the effect and on the number of rows; 1−β is the power of the test. For the ANOVA of k groups and n values in total, our engine computes it from the noncentral Fisher distribution:

1−β=P(F~k−1,n−k;λ>F1−α;k−1,n−k),λ=nη21−η2
(15)

where F1−α;k−1,n−k is the critical value of the test and F~ follows a Fisher distribution shifted by the noncentrality λ, with η2 the effect assumed in the population; our reports evaluate it at the observed η2, as information only. For a correlation ρ tested on n rows, it uses the noncentral Student distribution, an approximation of the distribution of r, and gives the number of rows needed for a power of 80% through Fisher’s transformation:

1−β=P(T~ν;δ>t1−α/2;ν)+P(T~ν;−δ>t1−α/2;ν),ν=n−2,δ=ρν1−ρ2,n1−β=⌈3+(z1−α/2+z1−β)2(artanh|ρ|)2⌉
(16)

Here zu is the quantile of order u of the standard normal distribution and T~ follows a Student distribution shifted by δ. For a partial correlation with c controls, our correlation engine replaces n−2 by n−2−c and searches the smallest n at which the noncentral formula itself reaches 80%. Both formulas were checked by simulation, not taken on trust. In the two situations of the box plots, the formula gave a power of 91.5% and 31.8%; the ANOVA rejected in 92.6% and 32.7% of the 2,000 simulated data sets, and the whole procedure of our engine, pre-tests included, in 92.5% and 32.5%. For correlations of 0.2, 0.3 and 0.5, the rows needed for 80% came out at 194, 85 and 30; at those sizes, Pearson’s test rejected in 79.1%, 80.9% and 83.0% of 4,000 simulated samples, a β close to 0.2, as intended; a little more power at 0.5, where Fisher’s approximation asks for 30 rows; the exact distribution of r reaches 80% at 29 rows, and the noncentral formula, an approximation, says 28.

Power is used before, not after. Computed at the effect observed, it is only a re-expression of the p-value (Hoenig and Heisey, 2001): our reports give it as information, never as the reason a result is not significant. What they give for each relation is the number of rows that would be needed to detect the effect observed with 80% power, and, for a correlation, its interval: an effect that the data cannot exclude is not an effect that has been ruled out.

Robustness: what holds when an assumption does not

Each assumption of a classical test has a fallback in our engines, chosen so that the result does not hang on one value or on one hypothesis:

  • Unequal variances: Welch’s tests, which do not pool them (formulas (1), (2) and (4)), and the pairwise comparisons of Games and Howell (formula (19)).
  • Values that are not normal: rank tests, which use only the order of the values, so that an extreme value counts as the largest, whatever its size (formulas (5) and (6)).
  • The test of equal variances itself: Levene’s, centred on the median, which an extreme value moves less than the mean.
  • A linear correlation carried by a few points: the rank correlation next to it, and, outside the time mode, a p-value by permutation that assumes no distribution (formula (17)).
  • Residuals whose spread changes: standard errors that do not assume a constant spread: HC3 for each pair of our correlation engine, and for an effect measured with controls when Breusch-Pagan’s test rejects; HC2 with corrected degrees of freedom on the innovations of a time series; errors robust by group when segments are pooled in time mode.
  • Sparse tables: the exact test when Cochran’s rule fails (formula (20)).
  • One influential point: Cook’s distance of each row in the fit of one variable on the other, reported with its threshold (formula (18)).

The permutation p-value shuffles one variable B times, 3,000 as shipped from a fixed seed, and counts how often the shuffled correlation is at least as strong as the one observed:

pperm=1+#{b≤B:|rb|≥|robs|}B+1(17)

and the influence of a row i, with ei its residual, hii its leverage and s2 the residual variance on n−2 degrees of freedom, is measured by Cook’s distance, where 2 is the number of coefficients of the fit of one variable on the other, the slope and the constant:

Di=ei22s2hii(1−hii)2(18)

For each pair, our correlation engine reports the largest of these distances and the largest DFBETAS, the change of the slope when the row is removed, divided by its standard error computed without that row, next to their usual thresholds 4/n and 2/n. These are diagnostics: no point is removed automatically, because a point that weighs heavily can be the most informative one; it is examined, as in step 5.

Robustness is measured, not assumed. The simulations of this article put each device to the test on data whose truth is known, and they show its limits as well: the excess of the two-step procedure when spreads differ (step 3), the rank tests that answer another question when shapes differ, the windows that only explore (step 4).

The paradoxes these steps avoid

Several traps of this article have a name, and each is handled at a precise step. Our article on statistical paradoxes tells how we check them in our code.

  • Galton’s problem: observations that are not independent, the rows of one customer or the dates of one series, counted as so many independent cases; handled by the unit of independence (step 1) and, in time, by the innovations (step 4).
  • Yule’s nonsense correlation: two trends that look linked; the levels are never tested (step 4).
  • Simpson’s paradox: a relation that reverses between the segments and the total; flagged (step 6).
  • The common cause: a correlation that a third variable creates; partial correlation on the declared controls (step 6).
  • Multiplicity: one chance in twenty of a false alarm at each test, multiplied by the number of tests; one adjusted family per question, before any filter (step 7).
  • The winner’s curse: the best window or the best category, chosen and judged on the same data, looks better than it is; the window stays exploratory and its p-value pays for the search (step 4), and a category is named only by an adjusted pairwise comparison (step 7).
  • The test chosen by the data: pre-tests on the same data change the level of the procedure; it is measured, not assumed (step 3).

No step protects against a factor nobody measured, nor against the way the rows were selected: these are questions of study design, not of computation.

What is decided from the data, and what simulations only confirm

Three kinds of choice coexist in these engines, and they should not be confused. Some are decided from the data at every run: which test, through the pre-tests of normality and variance; chi-square or exact test, through the expected counts; whether a series is differenced, through its two stationarity tests; the order of the autoregressive model that removes its dynamics, through the Akaike criterion; which categories enter a test, through the declared minimum count. Others are declared settings, chosen from the literature and never fitted to a data set: the level of the tests, the levels of the pre-tests, set apart from it, the minimum count of a category, Cochran’s thresholds, the number of draws and the seed of the exact test, the minimum length of a window. The minimum sizes of the list of findings, 0.1 and 0.2, are decision choices of the same kind, fixed in the code rather than drawn from the literature. Nothing here is tuned to make a simulation look good.

The simulations of this article are confirmations, not calibrations. They were run on the code as it is, on situations whose domain is stated, after the rules had been fixed. When we considered a different rule, sending every case of unequal variances to Welch’s tests even when normality fails (in two variants), its adoption criteria were written before the measurement: stay inside the simulation band wherever the current rule is inside it, come closer to 5% wherever it is outside, and lose no power. Measured over 4,000 simulations per situation, both variants improved the unequal-variance cases but left the band on others where the current rule held, so neither was adopted. A single revision of the protocol, declared before measuring, added a third variant: Welch’s tests whenever normality holds, without the variance pre-test. It brought the moderate cases from between 8.4% and 9.3% down to between 5.2% and 6% and made no situation worse, but it left the excess of the rank branch where it was, while the rule written in advance required an improvement in every situation outside the band, so it was not adopted either. On these situations it is the better rule, and we say so. Its own cost was measured too: with equal variances, Welch’s tests lose about 1.4 points of power with three balanced groups, and 2 to 5 points with unequal sizes. The remaining excess of the current rule is stated above instead of being tuned away.

What the engines do not claim

Known gaps are tracked, not hidden: no mixed models yet for data with several levels of grouping, no interval yet for most effect sizes, a residual excess of false alarms, about 7% and up to 9.3% in our measurements, when unequal spreads and sizes meet the pre-tests, rank tests that answer whether the distributions are the same rather than the means (with skewed groups of equal means and unequal spreads, they rejected between 33% and 71% of the time), two outputs, the share explained with controls in the first analysis and the automatic interactions of the correlation engine, that set an unusable control aside like the others but do not name it in the report yet, no automatic outlier analysis inside the engines, and, by design, no scan of lagged or rolling correlations. And a significant, adjusted, well-measured correlation is still not a cause. It can come from a factor nobody measured, from the way the rows were selected, or from a cause that runs the other way. Measuring the effect of a decision is a different question, with its own assumptions, treated in our article on treatment effects; a series that helps to predict another one is the subject of our time-series protocol. What our engines give is narrower and still valuable: which links are too strong to be chance, how strong they are, which ones a common cause explains, and which ones the data are too few to decide.

Technical details

After Welch’s t or Welch’s ANOVA, each pair of groups i and j is compared without assuming equal variances (Games-Howell). Its degrees of freedom are those of Welch and Satterthwaite:

νij=(si2/ni+sj2/nj)2(si2/ni)2ni−1+(sj2/nj)2nj−1(19)

and the difference of the two means, divided by si2/ni+sj2/nj and multiplied by 2, is read on the studentized range of all k groups with νij degrees of freedom, so that the whole family of pairs is controlled together. The effect of a pair is Bonett’s d, the difference of the means divided by (si2+sj2)/2, which does not assume equal variances either.

When Cochran’s rule fails, the exact test of independence conditions on the margins of the table. Given the margins, a table with cells nab has a probability proportional to 1/∏a,bnab!. The engine draws B tables 𝒯1,…,𝒯B with the margins of the observed table 𝒯obs, from a declared seed, and estimates

p^=1+#{b∣P(𝒯b)≤P(𝒯obs)}B+1,se(p^)=p^(1−p^)/B
(20)

The one added to the numerator and to the denominator makes p^ a valid p-value, never 0; the standard error is reported with it. The shipped setting draws 20,000 tables; the same table and the same seed always give the same p-value.

Annex: which test the engine reads, case by case

  • Two independent groups. Normal values and equal variances: Student’s t. Normal values, unequal variances: Welch’s t. Values not normal: Mann-Whitney, whose p-value is exact or approximate as the numerical library decides from the data; the result does not record which.
  • Three independent groups or more. Normal and equal variances: ANOVA, then Tukey’s pairwise comparisons. Normal, unequal variances: Welch’s ANOVA, then Games-Howell. Not normal: Kruskal-Wallis, then Dunn. Only the categories with at least the declared minimum count enter the test, its pre-tests, its effect size and its pairwise comparisons.
  • The same subjects, twice. Normal differences: paired t. Otherwise: Wilcoxon signed-rank, zero differences removed, with the same automatic choice of p-value. An outcome of 0 or 1: exact McNemar, on the pairs that changed.
  • The same subjects, three times or more. Normal residuals: repeated-measures ANOVA, with the Greenhouse-Geisser sphericity correction always applied rather than decided by a pre-test. Otherwise: Friedman; never Kruskal-Wallis, which would treat each subject as different people. An outcome of 0 or 1: Cochran’s Q test. Only the subjects observed at every level are kept.
  • Two categories. A 2 × 2 table: Fisher’s exact test, with the odds ratio and its interval. A larger table: chi-square when Cochran’s rule holds, otherwise the exact test of formula (20); Cramér’s V in both cases.
  • Two continuous measures. In our test engine, Pearson when both margins pass the normality check and the residuals keep a constant spread, Spearman otherwise (and below eight rows). Our correlation engine computes both and decides on the linear one, with the rank correlation and a permutation p-value next to it.
  • Two series in time. The test on the innovations of step 4, never on the levels.

References

Student (1908), “The probable error of a mean”, Biometrika; R. A. Fisher (1921), “On the probable error of a coefficient of correlation deduced from a small sample”, Metron; G. U. Yule (1926), “Why do we sometimes get nonsense-correlations between time-series?”, Journal of the Royal Statistical Society; F. E. Satterthwaite (1946), “An approximate distribution of estimates of variance components”, Biometrics Bulletin; H. B. Mann and D. R. Whitney (1947), “On a test of whether one of two random variables is stochastically larger than the other”, Annals of Mathematical Statistics; B. L. Welch (1947), “The generalization of ‘Student’s’ problem when several different population variances are involved”, Biometrika; B. L. Welch (1951), “On the comparison of several mean values: an alternative approach”, Biometrika; G. H. Freeman and J. H. Halton (1951), “Note on an exact treatment of contingency, goodness of fit and other problems of significance”, Biometrika; E. H. Simpson (1951), “The interpretation of interaction in contingency tables”, Journal of the Royal Statistical Society B; W. H. Kruskal and W. A. Wallis (1952), “Use of ranks in one-criterion variance analysis”, Journal of the American Statistical Association; W. G. Cochran (1954), “Some methods for strengthening the common χ² tests”, Biometrics; S. W. Greenhouse and S. Geisser (1959), “On methods in the analysis of profile data”, Psychometrika; H. Levene (1960), “Robust tests for equality of variances”, in Contributions to Probability and Statistics, Stanford University Press; W. L. Hays (1963), Statistics for Psychologists, Holt, Rinehart and Winston; S. S. Shapiro and M. B. Wilk (1965), “An analysis of variance test for normality (complete samples)”, Biometrika; R. D’Agostino and E. S. Pearson (1973), “Tests for departure from normality. Empirical results for the distributions of b₂ and √b₁”, Biometrika; M. B. Brown and A. B. Forsythe (1974), “Robust tests for the equality of variances”, Journal of the American Statistical Association; C. W. J. Granger and P. Newbold (1974), “Spurious regressions in econometrics”, Journal of Econometrics; H. Akaike (1974), “A new look at the statistical model identification”, IEEE Transactions on Automatic Control; L. D. Haugh (1976), “Checking the independence of two covariance-stationary time series: a univariate residual cross-correlation approach”, Journal of the American Statistical Association; P. A. Games and J. F. Howell (1976), “Pairwise multiple comparison procedures with unequal n’s and/or variances: a Monte Carlo study”, Journal of Educational Statistics; R. D. Cook (1977), “Detection of influential observation in linear regression”, Technometrics; G. M. Ljung and G. E. P. Box (1978), “On a measure of lack of fit in time series models”, Biometrika; T. S. Breusch and A. R. Pagan (1979), “A simple test for heteroscedasticity and random coefficient variation”, Econometrica; D. A. Dickey and W. A. Fuller (1979), “Distribution of the estimators for autoregressive time series with a unit root”, Journal of the American Statistical Association; W. M. Patefield (1981), “Algorithm AS 159: an efficient method of generating random r × c tables with given row and column totals”, Applied Statistics; L. V. Hedges (1981), “Distribution theory for Glass’s estimator of effect size and related estimators”, Journal of Educational Statistics; J. G. MacKinnon and H. White (1985), “Some heteroskedasticity-consistent covariance matrix estimators with improved finite sample properties”, Journal of Econometrics; J. Cohen (1988), Statistical Power Analysis for the Behavioral Sciences, 2nd edition, Lawrence Erlbaum; D. Kwiatkowski, P. C. B. Phillips, P. Schmidt and Y. Shin (1992), “Testing the null hypothesis of stationarity against the alternative of a unit root”, Journal of Econometrics; Y. Benjamini and Y. Hochberg (1995), “Controlling the false discovery rate: a practical and powerful approach to multiple testing”, Journal of the Royal Statistical Society B; J. M. Hoenig and D. M. Heisey (2001), “The abuse of power: the pervasive fallacy of power calculations for data analysis”, The American Statistician; R. M. Bell and D. F. McCaffrey (2002), “Bias reduction in standard errors for linear regression with multi-stage samples”, Survey Methodology; D. G. Bonett (2008), “Confidence intervals for standardized linear contrasts of means”, Psychological Methods; M. Tomczak and E. Tomczak (2014), “The need to report effect size estimates revisited: an overview of some recommended measures of effect size”, Trends in Sport Sciences.

Raphael Sebbah

About the author

Raphael Sebbah

Actuary (ISUP) and data scientist, founder of Smart Data Science. Formerly at Amundi (CAAM), Dexia, AIG and Phoenix; co-author of research published in The European Physical Journal C and Brain Communications.

LinkedIn · ORCID · Google Scholar

Let’s build better decisions together

Tell us about the decision you need to make.

A few lines are enough: your sector, the data you have and what you want to improve. We reply personally with a first view of the approach.

  • A few lines are enough
  • NDA on request
  • Code and documentation handed over