About this page
How-to guide- What this page solves
- You have June and August ozone data and want to know whether the two months differ. You are not sure whether to use a t test or a rank-sum test, and R and Python give different results.
- Who it is for
- Graduate students and researchers doing medical or biological statistics. They can run basic R or Python code but are not yet sure how to choose a test.
- What you will have
- After reading, you will have a record of why each test was chosen, reproducible two-group and multi-group results, and a results paragraph in SAMPL format.
- Covers
- Choosing a test by outcome type, number of groups, pairing and distribution
- Running two-group, multi-group, categorical, correlation and regression analyses
- Matching operations and default settings in R, Python and SPSS
- Common misuses, error messages and mismatched results
- Does not cover
- Mathematical derivations of statistical theory
- Sample size calculation and randomization design
- Building and validating prediction models
Main steps
Step 1
Why this stepWhat this step settles: which family of tests applies. “Paired” means the same subject is measured twice, or two matched subjects are compared. Paired observations are not independent, so they need separate analysis.
The full table is in the choices section, “Choose a test by research question”.
- 01
What type of outcome is it?
A continuous variable (such as concentration or blood pressure), an ordered grade (such as a response level), or a categorical variable (such as whether an event occurred). Each type allows different methods.
- 02
How many groups?
Two groups: a t test or a rank-sum test. Three or more: analysis of variance or Kruskal-Wallis. This page covers two groups first; the three-group steps are in step 4.
- 03
Are the data paired?
Before-and-after measurements on the same subject, or two methods applied to the same subject, are paired. Observations from two different populations are independent. The basis is how the data were generated.
Step 2
Why this stepWhat this step settles: whether to use a parametric method (t test, analysis of variance) or a rank-sum test. A rank-sum test ranks the data before comparing them, so it makes fewer assumptions about the distribution shape.
The June group has only 9 cases and is clearly right-skewed, which is the small skewed case above. So both methods are run: the Welch t test as the main analysis and the Mann-Whitney U test as a sensitivity analysis. Both reach the same conclusion, and both are reported.
The basis for judging distribution, and the limits of normality tests, are in the explanation section, “Why a normality test cannot decide the method alone”.
- 01
Count each group
Record how many valid values each group has. June has 9 and August has 26.
- 02
Plot a histogram and a Q-Q plot
When the data show clear skew, with one long tail, look at each group. In this example, both ozone groups are right-skewed.
- 03
Decide
Use a parametric method when the distribution is roughly symmetric or the samples are large. Use a rank-sum test as the alternative or sensitivity check when the skew is clear and the samples are small.
Step 3
Why this stepWhat this step settles: whether June and August ozone concentrations differ, and by how much. The Welch t test compares two group means without assuming equal variances, so it is the default for two groups.
The data come from R’s built-in airquality dataset. Keep only June and August rows with a recorded ozone value; the unit is ppb.
In R, t.test uses the Welch version by default, so no extra setting is needed.
If R and Python give different P values, see the troubleshooting entry “R and Python give different P values”.
library(effectsize)
aq <- subset(airquality, Month %in% c(6, 8) & !is.na(Ozone)); aq$Month <- factor(aq$Month)
t.test(Ozone ~ Month, data = aq) # R defaults to Welch
effectsize::hedges_g(Ozone ~ Month, data = aq, pooled_sd = FALSE)import pandas as pd
from scipy import stats
aq = pd.read_csv("airquality.csv").dropna(subset=["Ozone"])
x6, x8 = aq.Ozone[aq.Month == 6], aq.Ozone[aq.Month == 8]
print(stats.ttest_ind(x6, x8, equal_var=False)) # SciPy defaults to equal_var=True; set False explicitly for Welch- 01
Read and filter the data
Keep only June and August rows with a recorded ozone value. The two groups have 9 and 26 cases.
- 02
Run the Welch t test
Compare the two group means with t.test; in R this is already the Welch version. In Python, pass equal_var=False to request Welch. The CSV that Python reads is exported from R; the export code is in the reference section, “Runnable code”.
- 03
Compute the effect size and confidence interval
Use hedges_g with pooled_sd = FALSE, which does not pool the two SDs. The meaning of Hedges g is in the explanation section.
Step 4
Why this stepWhat this step settles: whether the three groups differ overall, and which pairs differ. This step switches to three-group data: R’s built-in PlantGrowth, with 10 plants per group and dry weight as the outcome. The groups are the control ctrl and two treatments, trt1 and trt2.
Analysis of variance (ANOVA) compares the means of several groups at once. It answers only whether all the groups are the same, not which pairs differ.
Post hoc tests answer which pairs differ. Use Tukey HSD when the variances are equal and Games-Howell when they are not. Report both.
The first row of the table is an uncorrected pairwise t test, shown for comparison. Its problem is in the troubleshooting section, “Pairwise t tests across three groups, with one pair at P < 0.05”.
fit <- aov(weight ~ group, data = PlantGrowth); summary(fit)
TukeyHSD(fit)
games_howell_test(PlantGrowth, weight ~ group) # post hoc test for unequal variancesimport pandas as pd
import pingouin as pg
pg_df = pd.read_csv("PlantGrowth.csv")
print(pg.anova(pg_df, dv="weight", between="group", detailed=True))
print(pg.pairwise_tukey(pg_df, dv="weight", between="group"))- 01
Run the overall test
Run a one-way ANOVA with aov and read the P value of the F test. It answers whether all groups are the same.
- 02
Then run post hoc tests
Use TukeyHSD when the variances are equal and games_howell_test when they are not. Post hoc tests answer which pairs differ. Report both.
- 03
Report the effect size
Both η² and ω² express the share of total variation explained by group differences; see the explanation section.
| Method (PlantGrowth, 3 groups of 10 plants) | ctrl vs trt1 | ctrl vs trt2 | trt1 vs trt2 |
|---|---|---|---|
| Pairwise Welch t-tests, unadjusted (incorrect) | P=0.250 | P=0.048 | P=0.009 |
| Pairwise Welch t-tests + Holm adjustment | P=0.250 | P=0.096 | P=0.028 |
| Tukey HSD (first choice with equal variances) | P=0.391 | P=0.198 | P=0.012 |
| Games-Howell (unequal variances) | P=0.475 | P=0.113 | P=0.024 |
Step 5
Why this stepWhat this step settles: turning the results into a results paragraph for a paper. Readers need the size of the difference, its interval and the P value together to judge what it means.
June and August ozone concentrations were 29.4 (18.2) and 60.0 (39.7) ppb. The mean difference was −30.5 ppb (95% CI −50.7 to −10.4).
Welch t test: t = −3.09, df = 30.0, P = 0.004. Hedges g = −0.96 (95% CI −1.61 to −0.30).
The full reporting checklist is in the reference section, “Reporting standards”.
If the two rows of SPSS output are unclear, see the troubleshooting entry “SPSS independent-samples t test shows two rows, and it is unclear which to read”.
Choose by your situation
Hand it to an agent
Data cleaning, test selection, double computation in R and Python and writing results in SAMPL format can be handed to the science agent; judgment and interpretation remain the researcher's job.
Example instruction: "Here is my clinical data, data.xlsx. The primary outcome is HbA1c at 6 months, comparing three treatment groups, with repeated measurements at baseline and 3 months. Choose tests by data type, compute them in both R and Python and cross-check, and write the results paragraph and tables following the SAMPL guidelines."
The agent works in an isolated cloud machine. It reads the data, checks missing values, outliers and variable types, draws histograms and Q-Q plots, and computes skewness and kurtosis. It then chooses tests from this page’s decision table, runs them in R and in Python, and compares P values, effect sizes and intervals item by item.
Where results differ, it traces the difference to a default setting. The project keeps the scripts, software versions, logs and intermediate results, and the results are reviewed adversarially. The task keeps running after your computer is turned off.
You still need to check: whether the unit of analysis matches the sampling unit; whether the primary and secondary outcomes match the protocol; the family of tests used for multiple comparison adjustment; and the clinical interpretation of the results.
Decision table
Determine the outcome type and the study design first, then look at the distribution. "First choice" is the approach most medical journal reviewers accept; "alternatives" apply when conditions are not met or as sensitivity analyses.
Decide between independent and paired by how the data were generated. The left and right side of the same animal, a patient before and after treatment, and cases and controls matched 1:1 on age and sex are all paired data. Several lesions, teeth or follow-up visits from the same patient are not independent observations either; the unit of analysis must match the unit of randomization or sampling.
When comparing two groups on an ordinal outcome (for example cured, markedly improved, improved, no effect), use the Mann-Whitney U test. A chi-squared test discards the ordering.
| Question | Outcome | Design | First choice | Alternatives and when to use them | Effect size to report |
|---|---|---|---|---|---|
| Compare two means | Continuous | Two independent groups | Welch's t-test | When sample sizes and variances are similar, Student's and Welch's t give almost the same result; for clearly skewed data with fewer than about 30 per group, use Mann-Whitney U | Mean difference with 95% CI, Hedges' g |
| Compare two distributions | Skewed continuous or ordinal | Two independent groups | Mann-Whitney U test (Wilcoxon rank-sum test) | Right-skewed concentrations or costs can be log-transformed and analyzed with Welch's t; interpret as a ratio of geometric means | Hodges-Lehmann shift with 95% CI, rank-biserial correlation |
| Before-after or matched comparison | Continuous | Paired (same or matched subjects) | Paired t-test | Wilcoxon signed-rank test when differences are clearly skewed | Mean difference with 95% CI, dz |
| Compare three or more means | Continuous | Several independent groups | One-way ANOVA + Tukey test | Welch's ANOVA + Games-Howell when variances differ; Dunnett when comparing only with a control | η² or ω², pairwise differences with 95% CI |
| Compare three or more distributions | Skewed continuous or ordinal | Several independent groups | Kruskal-Wallis test + Dunn test (Holm or Bonferroni adjustment) | Ordinal logistic regression for ordered categories | ε² or η²H |
| Compare several time points | Continuous | Repeated measures on the same subjects | Repeated-measures ANOVA, reporting Mauchly's test and the Greenhouse-Geisser correction | Linear mixed model with missing time points or uneven intervals; Friedman test for skewed data | Generalized η², means with 95% CI at each time point |
| Effects of two factors | Continuous | Factorial design | Two-way ANOVA with interaction (type III sums of squares) | State the sum-of-squares type for unbalanced designs; see the software section | Partial η², simple effects |
| Compare proportions between groups | Binary or nominal | Independent | Pearson chi-squared test | Fisher's exact test for 2×2 tables with expected counts below 5 or total n below 40; Fisher-Freeman-Halton exact test when more than 1/5 of cells in an R×C table have expected counts below 5 | Risk difference, RR or OR with 95% CI |
| Compare paired binary outcomes | Binary | Same subjects, two methods or before-after | McNemar's test | Exact binomial test when the number of discordant pairs b+c is small | Difference in discordant proportions or paired OR |
| Association of two continuous variables | Continuous | Two variables on the same subjects | Pearson correlation (linear, no marked outliers) | Spearman correlation for skewed, ordinal or outlier-prone data; repeated measurements per subject cannot be pooled | r with 95% CI |
| Agreement of two measurement methods | Continuous | Same subjects, two methods | Bland-Altman limits of agreement | Intraclass correlation coefficient (ICC); do not judge agreement with a correlation coefficient | Mean difference and 95% limits of agreement |
| Multivariable adjustment | Continuous | Any | Linear regression | Log-transform or use a generalized linear model for right-skewed outcomes | Coefficients with 95% CI, R² |
| Multivariable adjustment | Binary | Any | Logistic regression | When the outcome is common (above about 10%), the OR overstates the RR; use log-binomial or modified Poisson regression to report RR | OR with 95% CI |
| Survival time | Time + event indicator (censored) | Any | Kaplan-Meier curves + log-rank test; Cox regression for multivariable analysis | Piecewise or time-dependent covariates when proportional hazards fail | HR with 95% CI, median survival |
Skewed groups and repeated measures
For skewed data, compare several groups with a rank-based method. For repeated measurements on the same subjects, use a repeated-measures method. The two measured examples come from R’s built-in data; the five checklist points follow.
The Kruskal-Wallis test is the rank-based counterpart of one-way ANOVA, for skewed data. Using airquality ozone from May to September (n = 116): H = 29.27, df = 4, P = 6.9×10⁻⁶, η²H = 0.23. Post hoc Dunn tests with Holm correction show differences between May and July, May and August, July and September, and August and September.
Repeated-measures data call for a repeated-measures ANOVA or the Friedman test. Using Indometh (6 subjects, indomethacin plasma concentrations at 0.5, 1, 2, 4 and 8 hours): Mauchly test W = 0.00063, P = 0.0059, so the sphericity assumption does not hold. Uncorrected F(4, 20) = 106.6; Greenhouse-Geisser ε = 0.378, corrected degrees of freedom 1.51 and 7.55, P = 4.7×10⁻⁶. R’s afex::aov_ez and pingouin.rm_anova agree. Friedman test χ² = 24.0, P = 8.0×10⁻⁵.
Report the correction method and the ε value used. For judging and correcting sphericity, see the troubleshooting entry “In repeated-measures ANOVA, Mauchly’s sphericity test gives P < 0.05”.
- The Tukey test works with unequal group sizes (Tukey-Kramer method); R's TukeyHSD and SPSS's Tukey handle this automatically.
- When only comparing each treatment with one control, use Dunnett's test: fewer comparisons and more power than Tukey.
- The LSD method controls the familywise error rate only with exactly 3 groups and a significant overall F test; do not use it with more groups.
- The SNK method does not control the familywise error rate when only some group means are equal; reviewers often ask for Tukey or Holm instead.
- With dropouts, repeated-measures ANOVA deletes the whole subject; a linear mixed model uses incomplete observations.
Correcting for multiple comparisons
The right correction depends on how the comparisons are structured and on the purpose of the study. The table lists common methods by situation.
Six of these raw P values are below 0.05; only the first remains after Bonferroni or Holm adjustment, and the first three after BH adjustment. In the paper, state the adjustment method and the family of tests adjusted (for example, "Holm adjustment for the 6 between-group comparisons of 3 secondary outcomes"), and report adjusted P values or the adjusted significance level.
raw P Bonferroni Holm BH(FDR)
0.001 0.010 0.010 0.0100
0.008 0.080 0.072 0.0400
0.012 0.120 0.096 0.0400
0.021 0.210 0.147 0.0525
0.035 0.350 0.210 0.0700
0.048 0.480 0.240 0.0800
0.090 0.900 0.360 0.1286
0.200 1.000 0.600 0.2500
0.410 1.000 0.820 0.4556
0.740 1.000 0.820 0.7400| Situation | Method | Notes |
|---|---|---|
| All pairwise comparisons after ANOVA | Tukey (Games-Howell with unequal variances) | Uses the error estimate from all groups and has more power than adjusting each pair separately |
| Each group compared only with one control | Dunnett | Number of comparisons is the number of groups minus 1 |
| A few pre-planned comparisons, or a mix of different tests | Holm | Controls the familywise error rate, is never less powerful than Bonferroni and needs no extra assumptions, so it can replace Bonferroni |
| Exploratory screening of dozens of outcomes, genes or imaging regions | Benjamini-Hochberg (FDR) | Controls the proportion of false positives among positive results; confirm findings in independent data |
| Confirmatory study with a single primary outcome | No adjustment | Pre-specify it in the protocol or statistical analysis plan |
| Exploratory analyses, secondary outcomes | May be left unadjusted but labeled exploratory | Recommended by Bender and Lange (2001); the NEJM 2019 statistical guidelines require secondary outcomes without a pre-specified adjustment method to be reported as estimates with 95% CIs only |
Categorical variables
For a 2×2 table, check the total count and the smallest expected count before choosing a test.
Chinese medical statistics textbooks give these four-cell rules: with n ≥ 40 and all expected counts T ≥ 5, use the Pearson chi-square; with n ≥ 40 and 1 ≤ T < 5, use the continuity-corrected chi-square; with n < 40 or any T < 1, use Fisher’s exact test. An R×C table needs no cell with T < 1, and at most 1/5 of cells may have 1 ≤ T < 5. For a paired 2×2 table with b + c < 40, use the McNemar correction formula.
Campbell (2007, Stat Med) compared methods by simulation and found the Yates correction too conservative. He recommended the N−1 chi-squared test (Pearson χ² multiplied by (N−1)/N) when all expected counts are at least 1, and the Fisher test otherwise. For Chinese journals, follow the textbook rule; for international journals, Fisher's exact test or the uncorrected chi-squared can be reported directly with the reason stated.
When reporting an OR from the Fisher test, note that R gives the conditional maximum likelihood estimate and SciPy gives the sample OR ad/bc; with small samples they differ noticeably (8.15 vs 9.33). State how the OR and its 95% CI were computed, or estimate it with logistic regression throughout.
McNemar's test (the 1600-person repeated poll from the R help page, discordant pairs b=150, c=86): continuity-corrected χ²=16.82, P=4.1×10⁻⁵; uncorrected χ²=17.36, P=3.1×10⁻⁵; exact binomial test on discordant pairs P=3.7×10⁻⁵. R's mcnemar.test applies the correction by default, while statsmodels' mcnemar defaults to exact=True, so the default results differ.
| Data (tested on this page) | Pearson χ² (uncorrected) | Yates-corrected χ² | Fisher's exact test | OR estimate |
|---|---|---|---|---|
| infert: history of spontaneous abortion × case/control (n=248, smallest expected count 35.8) | χ²=27.18, P=1.8×10⁻⁷ | χ²=25.79, P=3.8×10⁻⁷ | P=3.5×10⁻⁷ | R fisher.test conditional MLE OR=4.24 (95% CI 2.35 to 7.80); scipy fisher_exact sample OR=4.27 |
| Constructed small table [[7,3],[2,8]] (n=20, expected counts 4.5 and 5.5) | — | χ²=3.23, P=0.072; R warns Chi-squared approximation may be incorrect | P=0.070 | R conditional OR=8.15; scipy sample OR=9.33 |
Correlation and regression
A correlation coefficient describes the strength of a linear or monotonic association; a regression coefficient describes an effect size adjusted for other variables. Neither alone supports a causal conclusion.
The number of predictors in logistic and Cox regression is limited by the number of events. Peduzzi et al. (1996) proposed at least 10 events per variable (EPV≥10) from simulation; later work treats this only as a rough lower bound, and sample sizes for prediction models should be calculated with the method of Riley et al. Putting 10 predictors into a model with only 30 events gives severely biased coefficients.
Pearson and Spearman (measured on this page)
Ozone and temperature in airquality (n = 116): Pearson r = 0.698 (95% CI 0.591 to 0.781), Spearman ρ = 0.774. Ozone is right-skewed, and the gap between the two suggests a monotonic but nonlinear relationship.
Linear regression (tested on this page)
log(ozone) ~ temperature + wind: temperature coefficient 0.0574 (95% CI 0.0446 to 0.0702), so each 1°F rise increases ozone by about exp(0.0574)−1=5.9%; wind coefficient −0.0525 (95% CI −0.0865 to −0.0186); R²=0.582. R's lm and statsmodels' ols agree. Coefficients on a log-transformed outcome are read as percentage changes.
Logistic regression (measured on this page)
infert data: each additional spontaneous abortion multiplies the odds by OR = 3.37 (Wald 95% CI 2.22 to 5.12), P = 1.2×10⁻⁸. Wald and profile-likelihood intervals are close in large samples, but differ clearly in small samples or when OR is large; see the troubleshooting section.
Cox regression (measured on this page)
survival::lung (n = 228, 165 events): women vs men HR = 0.599 (95% CI 0.431 to 0.831), P = 0.0022; age HR = 1.017 (95% CI 0.999 to 1.036), P = 0.065. The global cox.zph test gives P = 0.25, so the proportional hazards assumption was not rejected.
Principal component analysis
Principal component analysis (PCA) combines several correlated continuous variables into a few uncorrelated composite variables, for dimension reduction, composite indices or handling collinearity before regression. It describes the variance structure of the variables and tests no hypothesis.
R's prcomp returns eigenvectors in rotation, while the SPSS "component matrix" from the Factor menu with principal components extraction contains loadings. To get the coefficients of the component equations from the SPSS component matrix, divide each column by the square root of its eigenvalue. sklearn's explained_variance_ uses n−1 as the divisor while StandardScaler standardizes with n, so here sklearn's first eigenvalue is 2.622 versus the correlation-matrix eigenvalue 2.613; the proportions of variance explained are unaffected.
library(survival)
labs <- c("bili", "chol", "albumin", "copper", "alk.phos", "ast", "trig", "platelet", "protime")
pb <- na.omit(pbc[, labs]) # 276 complete cases
pca <- prcomp(pb, scale. = TRUE) # standardize: the variables have different units
summary(pca) # proportion and cumulative proportion of variance
eig <- pca$sdev^2 # eigenvalues
loadings <- sweep(pca$rotation, 2, pca$sdev, "*") # loadings = eigenvectors x sqrt(eigenvalues), i.e. the SPSS component matrix
round(loadings[, 1:2], 3)
# Parallel analysis: keep components whose eigenvalue exceeds the 95th percentile of random data
set.seed(2026)
sim <- replicate(500, eigen(cor(matrix(rnorm(nrow(pb) * ncol(pb)), nrow(pb))))$values)
rbind(observed = round(eig, 3), random95 = round(apply(sim, 1, quantile, 0.95), 3))import numpy as np, pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
pb = pd.read_csv("pbc_labs.csv") # exported in R with write.csv(na.omit(pbc[, labs]), ...)
pca = PCA().fit(StandardScaler().fit_transform(pb))
print(pca.explained_variance_ratio_.round(4)) # same as Proportion of Variance in R summary(pca)
eig = np.linalg.eigvalsh(np.corrcoef(pb.T.to_numpy()))[::-1] # eigenvalues of the correlation matrix, same as R and SPSS
loadings = pca.components_.T * np.sqrt(eig) # signs may be flipped relative to R; interpret relative directions
print(pd.DataFrame(loadings[:, :2], index=pb.columns, columns=["PC1", "PC2"]).round(3))- 01
Check that PCA applies
Variables are continuous and moderately correlated (most |r|>0.3 in the correlation matrix). A common rule of thumb is a sample size of at least 5 to 10 times the number of variables. The KMO measure and Bartlett's test of sphericity come from factor analysis; they can be consulted for PCA but are not required.
- 02
Standardize first
Variables with different units must be standardized (scale. = TRUE in R, i.e. a correlation-matrix PCA). On the PBC data (9 laboratory variables from survival::pbc, 276 complete cases): without standardization, the first component explains 98.3% of the variance, almost all from alkaline phosphatase, which has the largest values and a loading of −1.000; after standardization the first component explains 29.0%.
- 03
Decide how many components to keep
The standardized eigenvalues are 2.613, 1.483, 0.991, 0.876 and so on. The Kaiser rule (eigenvalue >1) keeps 2; parallel analysis (comparison with the 95th percentiles of eigenvalues from random data of the same size, 1.362, 1.249, 1.165) also keeps 2. The third eigenvalue, 0.991, is close to 1; the Kaiser rule is unstable in such borderline cases and parallel analysis is more reliable. A cumulative 85% of variance is a common criterion in Chinese tutorials; here the first 2 components explain only 45.5% cumulatively, so these variables cannot be summarized by a few components.
- 04
Read the loadings
A loading is the correlation between a variable and a component, equal to the eigenvector multiplied by the square root of its eigenvalue. Here bilirubin (0.836), copper (0.661), AST (0.618), triglycerides (0.561) and cholesterol (0.527) load strongly on the first component and albumin at −0.476, which can be read as severity of liver damage; the second component is mainly platelets (0.756), prothrombin time (−0.533) and cholesterol (0.513). Component signs are arbitrary: the first component has opposite signs in R and Python, so interpret the relative directions of variables.
- 05
Report
Report the standardization, the number of components kept and why, the eigenvalue and variance explained for each component, and the loading matrix (usually listing variables with |loading|≥0.4). When component scores enter a regression, state how the scores were computed.
Concepts and judgment
Explained: normality tests
t-tests and ANOVA require approximate normality within each group (or of regression residuals), not of all data pooled. In large samples they are quite robust to non-normality; the main risk is unequal variances combined with unequal sample sizes.
A normality test’s P value changes with sample size: a tiny departure can be “significant” in a large sample, and a clear departure can go undetected in a small one. Judge by plots, skewness and kurtosis, together with sample size.
Sensitivity of normality tests to sample size (tested on this page)
Sampling from a t distribution with 10 degrees of freedom (only mildly heavy-tailed), set.seed(2026): Shapiro-Wilk P=0.60 at n=30, P=0.42 at n=100, P=0.0019 at n=1000 and P=8.6×10⁻¹² at n=5000. Over 200 repetitions, 12% of samples were judged non-normal at n=30 and 100% at n=5000. The distribution is the same; only the sample size changes the conclusion.
Thresholds for skewness and kurtosis
Kim (2013, Restor Dent Endod): for n<50, an absolute z value of skewness or kurtosis above 1.96 indicates non-normality; for 50≤n<300 the threshold is 3.29; for n≥300, ignore z values and look at the histogram and whether absolute skewness exceeds 2 or absolute kurtosis exceeds 7. Shapiro-Wilk and K-S tests suit samples with n<300.
How large is large enough to ignore normality
Lumley et al. (2002, Annu Rev Public Health) reviewed simulation studies and concluded that the sample size needed for t-tests and linear regression is often under 100, and under 500 even for extremely skewed medical cost data. This assumes the variances are not very different, or that Welch's t-test and robust standard errors are used.
Explained: Welch t test
In the June vs August comparison, the larger August group also has the larger variance. The Student t test pools the two variances, which favours the large group, overestimates the standard error and inflates the P value (0.034 vs 0.0043).
Conversely, if the smaller group has the larger variance, the Student t P value becomes too small and false positives increase. Welch t does not require checking the variances first in either case.
Explained: effect size and confidence interval
An effect size measures how large a difference is, and does not depend on sample size. A 95% confidence interval gives the plausible range of the difference; a narrower interval means a more precise estimate.
For two group means, use Hedges g, which is less biased than Cohen’s d in small samples. For paired designs, dz is common: the mean of the differences divided by the SD of the differences.
Cohen’s cut-offs of 0.2, 0.5 and 0.8 for small, medium and large come from behavioural science. In medical research, interpret the difference first in its original unit, and compare it with the minimal clinically important difference.
Explained: multiple comparisons
For 10 independent tests where every null hypothesis is true, the chance that at least one gives P < 0.05 is 1 − 0.95¹⁰ = 40%.
The more comparisons you make, the more likely a false positive becomes. Define the comparison set in advance and correct for it. Correction methods are in the choices section, “Correcting for multiple comparisons”.
Reference and appendix
Measured data
Tested on this page: R 4.4.3 (car 3.1.5, effectsize 1.0.3, rstatix 1.1.0, afex 1.5.1, survival 3.8.12) and Python 3.12 (SciPy 1.18.1, statsmodels 0.15.0, pingouin 0.7.0, lifelines 0.30.3) on macOS arm64. The data are R built-in datasets exported to CSV so both languages read identical data. The data are ozone concentrations (ppb) from airquality, right-skewed and with clearly different variances between months.
Effect sizes and confidence intervals: May vs August mean difference −36.3 ppb (Welch 95% CI −54.4 to −18.3), Hedges' g=−1.11 (95% CI −1.69 to −0.53); June vs August mean difference −30.5 ppb (95% CI −50.7 to −10.4), Hedges' g with unpooled SD −0.96 (95% CI −1.61 to −0.30).
| Comparison | n, mean (SD) per group | Student's t | Welch's t | Mann-Whitney U | R and Python agree? |
|---|---|---|---|---|---|
| May vs August (equal n) | 26, 23.6 (22.2); 26, 60.0 (39.7) | t=−4.075, df=50, P=0.000165 | t=−4.075, df=39.3, P=0.000217 | W=127.5, P=0.000121 | Yes (SciPy and pingouin match to 6 decimal places) |
| June vs August (unequal n) | 9, 29.4 (18.2); 26, 60.0 (39.7) | t=−2.211, df=33, P=0.034 | t=−3.092, df=30.0, P=0.0043 | W=57.5, P=0.026 | Yes |
Software comparison
The three packages use different defaults for the same method, so the same data can give different P values. R and Python results in the table were run on this page; SPSS menus were checked against IBM documentation and not run locally.
| Method | R | Python | SPSS menu | Default differences |
|---|---|---|---|---|
| Welch t / Student t | t.test(y ~ g); var.equal = TRUE for Student | scipy.stats.ttest_ind(a, b, equal_var=False); pingouin.ttest | Analyze > Compare Means > Independent-Samples T Test | R defaults to Welch; SciPy defaults to Student; pingouin's correction='auto' uses Welch only when sample sizes differ; SPSS prints both rows |
| Mann-Whitney U | wilcox.test(y ~ g) | scipy.stats.mannwhitneyu; pingouin.mwu | Analyze > Nonparametric Tests > Independent Samples | With ties, R and SciPy both use the normal approximation with continuity correction; same P on this page (0.000121) |
| Paired t / Wilcoxon signed-rank | t.test(x, y, paired = TRUE); wilcox.test(x, y, paired = TRUE) | scipy.stats.ttest_rel; scipy.stats.wilcoxon | Analyze > Compare Means > Paired-Samples T Test; Nonparametric Tests > Related Samples | With zero differences and ties, R uses the normal approximation with correction (P=0.0091) while SciPy 1.18 gives an exact P by default (0.0039); method='approx', correction=True matches R |
| One-way ANOVA / Welch's ANOVA | aov; oneway.test | pingouin.anova; pingouin.welch_anova | Analyze > Compare Means > One-Way ANOVA (tick Welch under Options) | Same results |
| Post hoc tests | TukeyHSD; rstatix::games_howell_test; rstatix::dunn_test | pingouin.pairwise_tukey; pairwise_gameshowell; statsmodels pairwise_tukeyhsd | One-Way ANOVA Post Hoc: Tukey, Dunnett, Games-Howell | Same results |
| Multi-factor ANOVA | car::Anova(lm(...), type = 3) with contr.sum | statsmodels anova_lm(typ=3) with C(x, Sum); pingouin.anova defaults to type II | Analyze > General Linear Model > Univariate (type III by default) | R's aov and statsmodels default to type I (sequential) sums of squares; in unbalanced designs the result depends on variable order, see the test below |
| Repeated-measures ANOVA | afex::aov_ez | pingouin.rm_anova(correction=True) | Analyze > General Linear Model > Repeated Measures | Same results; all report Mauchly's test and the GG correction |
| Chi-squared / Fisher | chisq.test; fisher.test | scipy.stats.chi2_contingency; fisher_exact | Analyze > Descriptive Statistics > Crosstabs > Statistics: Chi-square | R and SciPy apply Yates by default for 2×2 tables; Fisher OR definitions differ (conditional MLE vs sample OR) |
| McNemar | mcnemar.test | statsmodels mcnemar | Crosstabs > Statistics: McNemar | R defaults to the continuity-corrected chi-squared, statsmodels to the exact binomial test |
| Correlation | cor.test(method = 'pearson' / 'spearman') | scipy.stats.pearsonr; pingouin.corr | Analyze > Correlate > Bivariate | Same results; pingouin reports the 95% CI directly |
| Linear / logistic regression | lm; glm(family = binomial) | statsmodels ols; logit | Analyze > Regression > Linear; Binary Logistic | R's confint(glm) gives profile-likelihood intervals; statsmodels and SPSS give Wald intervals |
| Cox regression | survival::coxph | lifelines.CoxPHFitter; statsmodels PHReg | Analyze > Survival > Cox Regression | R and lifelines default to Efron ties, statsmodels to Breslow |
| Multiple comparison adjustment | p.adjust(p, 'holm' / 'BH') | statsmodels multipletests(method='holm' / 'fdr_bh') | Bonferroni built into some procedures | Same results |
| Principal component analysis | prcomp(x, scale. = TRUE) | sklearn PCA + StandardScaler | Analyze > Dimension Reduction > Factor (extraction: principal components) | R's rotation and sklearn's components_ are eigenvectors; the SPSS component matrix contains loadings; sklearn's explained_variance_ is n/(n−1) times the correlation-matrix eigenvalues |
Reporting standards
Compiled from the SAMPL guidelines (Lang and Altman). Where the target journal has its own statistical requirements, follow the journal.
| Result type | Example wording (data tested on this page) |
|---|---|
| Two-group means | Ozone concentrations in June and August were 29.4 (18.2) and 60.0 (39.7) ppb; mean difference −30.5 ppb (95% CI −50.7 to −10.4), Welch t=−3.09, df=30.0, P=0.004, Hedges' g=−0.96 (95% CI −1.61 to −0.30). |
| Paired comparison | Drug 2 increased sleep by 1.58 hours more than drug 1 (95% CI 0.70 to 2.46), paired t=4.06, df=9, P=0.003. |
| Several groups | Dry weight differed among the 3 groups, F(2, 27)=4.85, P=0.016, ω²=0.20; Tukey tests showed trt2 was 0.87 g higher than trt1 (95% CI 0.17 to 1.56, adjusted P=0.012). |
| Proportions | A history of spontaneous abortion was more common among cases than controls, OR=4.24 (95% CI 2.35 to 7.80), Fisher's exact test P<0.001. |
| Survival | After adjustment for age, women had a lower risk of death than men, HR=0.60 (95% CI 0.43 to 0.83), P=0.002. |
- Report P values as equalities: P=0.03, P=0.22, not P<0.05 or "NS". The smallest P value that needs reporting is P<0.001, except in genetic association studies.
- For primary outcomes, report effect estimates with 95% CIs, such as mean differences, risk differences, ORs and HRs.
- State which method was used for each analysis instead of listing all method names at the end of the statistics paragraph.
- State whether tests were one- or two-sided (justify one-sided tests), the alpha level, and whether and how multiple comparisons were adjusted.
- State how assumptions were checked: skewed data were analyzed with nonparametric methods, paired data with paired methods, and linear regression checked for linearity and residuals.
- Give numerators and denominators for percentages and the sample size for each analysis.
- Name the statistical software and version, for example R 4.4.3 (car 3.1) or SPSS 27.0.
- Label post hoc and unplanned subgroup analyses as exploratory.
Runnable code
The code below ran in this page's test environment. The R code uses built-in datasets directly; the Python code reads CSV files exported from R so both sides use identical data.
# R 4.4:install.packages(c("car", "effectsize", "rstatix", "afex", "survival"))
library(car); library(effectsize); library(rstatix); library(afex); library(survival)
# Two independent groups: airquality ozone, June (n=9) vs August (n=26)
aq <- subset(airquality, Month %in% c(6, 8) & !is.na(Ozone)); aq$Month <- factor(aq$Month)
t.test(Ozone ~ Month, data = aq) # R defaults to Welch
t.test(Ozone ~ Month, data = aq, var.equal = TRUE) # Student t, the first row in SPSS
wilcox.test(Ozone ~ Month, data = aq, conf.int = TRUE)
effectsize::hedges_g(Ozone ~ Month, data = aq, pooled_sd = FALSE)
# Paired: sleep data, same subjects under two drugs
w <- reshape(sleep, idvar = "ID", timevar = "group", direction = "wide")
t.test(w$extra.2, w$extra.1, paired = TRUE)
wilcox.test(w$extra.2, w$extra.1, paired = TRUE, exact = FALSE)
# Several groups: one-way ANOVA, Welch ANOVA, post hoc tests, Kruskal-Wallis + Dunn
fit <- aov(weight ~ group, data = PlantGrowth); summary(fit)
oneway.test(weight ~ group, data = PlantGrowth) # Welch ANOVA
TukeyHSD(fit)
games_howell_test(PlantGrowth, weight ~ group) # post hoc test for unequal variances
effectsize::omega_squared(fit)
aq_all <- subset(airquality, !is.na(Ozone)); aq_all$Month <- factor(aq_all$Month)
kruskal.test(Ozone ~ Month, data = aq_all)
dunn_test(aq_all, Ozone ~ Month, p.adjust.method = "holm")
# Repeated measures: Indometh, 6 subjects at 5 time points
ind <- subset(as.data.frame(Indometh), time %in% c(0.5, 1, 2, 4, 8))
ind$Subject <- factor(as.character(ind$Subject)); ind$time <- factor(ind$time)
rm <- aov_ez(id = "Subject", dv = "conc", data = ind, within = "time")
summary(rm) # Mauchly test and GG/HF corrections
friedman.test(conc ~ time | Subject, data = ind)
# Categorical: chi-squared, Fisher, McNemar
tab <- table(infert$spontaneous > 0, infert$case)
chisq.test(tab)$expected # check expected counts first
chisq.test(tab, correct = FALSE); fisher.test(tab)
mcnemar.test(matrix(c(794, 86, 150, 570), 2))
# Correlation and regression
cor.test(aq_all$Ozone, aq_all$Temp) # Pearson, with 95% CI
cor.test(aq_all$Ozone, aq_all$Temp, method = "spearman", exact = FALSE)
m <- lm(log(Ozone) ~ Temp + Wind, data = aq_all); summary(m); confint(m)
g <- glm(case ~ spontaneous + induced + age, family = binomial, data = infert)
exp(cbind(OR = coef(g), confint.default(g)))
cx <- coxph(Surv(time, status) ~ age + sex, data = lung); summary(cx); cox.zph(cx)
# Multiple comparison adjustment
p <- c(0.001, 0.008, 0.012, 0.021, 0.035, 0.048, 0.09, 0.2, 0.41, 0.74)
round(cbind(p, bonf = p.adjust(p, "bonferroni"), holm = p.adjust(p, "holm"), BH = p.adjust(p, "BH")), 4)library(survival)
write.csv(airquality, "airquality.csv", row.names = FALSE); write.csv(sleep, "sleep.csv", row.names = FALSE)
write.csv(PlantGrowth, "PlantGrowth.csv", row.names = FALSE); write.csv(as.data.frame(Indometh), "Indometh.csv", row.names = FALSE)
write.csv(infert, "infert.csv", row.names = FALSE); write.csv(lung, "lung.csv", row.names = FALSE)# Python 3.12:pip install scipy statsmodels pingouin pandas lifelines
# Export the data from R first: write.csv(airquality, "airquality.csv", row.names = FALSE), etc.
import numpy as np, pandas as pd, pingouin as pg
from scipy import stats
import statsmodels.formula.api as smf
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.contingency_tables import mcnemar
aq = pd.read_csv("airquality.csv").dropna(subset=["Ozone"])
x6, x8 = aq.Ozone[aq.Month == 6], aq.Ozone[aq.Month == 8]
print(stats.ttest_ind(x6, x8, equal_var=False)) # SciPy defaults to equal_var=True; set False explicitly for Welch
print(pg.ttest(x6, x8, correction=True)) # pingouin default 'auto' uses Welch only when sample sizes differ
print(stats.mannwhitneyu(x6, x8))
sleep = pd.read_csv("sleep.csv").pivot(index="ID", columns="group", values="extra")
print(stats.ttest_rel(sleep[2], sleep[1]))
print(stats.wilcoxon(sleep[2], sleep[1], method="approx", correction=True)) # matches the R default
pg_df = pd.read_csv("PlantGrowth.csv")
print(pg.anova(pg_df, dv="weight", between="group", detailed=True))
print(pg.welch_anova(pg_df, dv="weight", between="group"))
print(pg.pairwise_tukey(pg_df, dv="weight", between="group"))
print(pg.pairwise_gameshowell(pg_df, dv="weight", between="group"))
print(pg.kruskal(aq, dv="Ozone", between="Month"))
ind = pd.read_csv("Indometh.csv"); ind = ind[ind.time.isin([0.5, 1, 2, 4, 8])]
print(pg.rm_anova(ind, dv="conc", within="time", subject="Subject", correction=True))
print(pg.friedman(ind, dv="conc", within="time", subject="Subject"))
inf = pd.read_csv("infert.csv")
tab = pd.crosstab(inf.spontaneous > 0, inf.case).to_numpy()
chi2, p, dof, expected = stats.chi2_contingency(tab, correction=False); print(chi2, p, expected.round(1))
print(stats.fisher_exact(tab))
print(mcnemar(np.array([[794, 150], [86, 570]]), exact=False, correction=True))
print(pg.corr(aq.Ozone, aq.Temp), pg.corr(aq.Ozone, aq.Temp, method="spearman"))
print(smf.ols("np.log(Ozone) ~ Temp + Wind", data=aq).fit().summary())
logit = smf.logit("case ~ spontaneous + induced + age", data=inf).fit(disp=0)
print(np.exp(pd.concat([logit.params, logit.conf_int()], axis=1)))
from lifelines import CoxPHFitter
lung = pd.read_csv("lung.csv")[["time", "status", "age", "sex"]].dropna(); lung["status"] -= 1
print(CoxPHFitter().fit(lung, "time", "status").summary[["exp(coef)", "exp(coef) lower 95%", "exp(coef) upper 95%", "p"]])
p = [0.001, 0.008, 0.012, 0.021, 0.035, 0.048, 0.09, 0.2, 0.41, 0.74]
for m in ["bonferroni", "holm", "fdr_bh"]: print(m, multipletests(p, method=m)[1].round(4))Troubleshooting by error message or symptom
Each entry starts from what you see: a symptom or the error text. Cause and fix are listed separately, roughly in order of how often they occur.
SPSS independent-samples t test shows two rows, and it is unclear which to read
Cause: SPSS outputs two rows, “equal variances assumed” and “equal variances not assumed”, with different t and P values. Switching between them based on Levene’s test changes the type I error rate.
Fix: Read the “equal variances not assumed” row, which is the Welch t test. When variances are equal, Welch loses very little power.
R and Python give different P values
Cause: Most differences come from default settings: SciPy’s ttest_ind defaults to Student t, while R defaults to Welch; the Wilcoxon signed-rank test uses different defaults when zero differences occur; McNemar’s test uses different default corrections; R’s aov uses type I sums of squares by default.
Fix: Check the matching table in the reference section, “Operations and defaults in different statistical software”, and set the parameters to match. Once they match, every test on this page gives the same result.
Pairwise t tests across three groups, with one pair at P < 0.05
Cause: More pairwise comparisons means more false positives. Measured on PlantGrowth: ctrl vs trt2 gives P = 0.048 with uncorrected t tests, and P = 0.198 after Tukey correction.
Fix: Run an ANOVA or Kruskal-Wallis test first, then use Tukey, Games-Howell, Dunnett or Dunn tests for pairwise comparisons.
Paired data analysed with an independent-samples t test: P goes from 0.0028 to 0.079
Cause: The standard error is estimated wrongly. Differences between individuals are not removed, so a real difference can go undetected. Analysing repeated time points of one patient with ordinary ANOVA, or treating several lesions from one patient as separate samples, is the same error.
Fix: Use a paired t test, repeated-measures ANOVA or a mixed model, so that the analysis unit matches the sampling unit. Measured on the sleep data: paired t test t = 4.06, df = 9, P = 0.0028, mean difference 1.58 hours (95% CI 0.70 to 2.46); an independent-samples t test gives P = 0.079.
Shapiro-Wilk gives P < 0.05, so every variable is switched to a rank-sum test
Cause: With a large sample, a tiny departure gives P < 0.05; with a small sample, a serious departure can go undetected. The result mostly reflects sample size.
Fix: Look at the Q-Q plot and histogram, together with skewness and kurtosis. With large samples, use the t test or ANOVA directly.
Levene test first: Student t if P > 0.05, otherwise Welch t
Cause: The two-stage choice itself changes the type I error rate. Levene’s test has low power in small samples.
Fix: Use the Welch t test directly. It loses little power when variances are equal, and keeps the type I error rate closer to the nominal level when they are not.
The normality test result on this dataset decides between a t test and a rank-sum test
Cause: Simulations by Rochon et al. (2012) argue that this two-stage approach is formally incorrect.
Fix: Decide in advance from previous studies, a pilot study or the nature of the variable. When unsure, use the nonparametric test directly.
The paper says the medians differ, but only a Mann-Whitney U test was run
Cause: When the shapes or spreads of the two distributions differ, a significant test does not mean the medians differ (Hart 2001).
Fix: Report each group’s median and quartiles, and describe the difference with the Hodges-Lehmann location shift.
After a significant Kruskal-Wallis test, pairwise Mann-Whitney tests are run without correction
Cause: Uncorrected pairwise comparisons inflate the false-positive rate, the same problem as pairwise t tests after an ANOVA.
Fix: Use Dunn tests with Holm correction. The measured airquality example is in the section “Skewed groups and repeated measures”.
The Levene F value differs from SPSS (9.50 vs 10.09)
Cause: R’s car::leveneTest and SciPy’s stats.levene center on the median by default (Brown-Forsythe test); SPSS’s independent-samples t test outputs the classic Levene test centred on the mean.
Fix: To match SPSS, add center = mean in R. Measured on airquality, May vs August: median-centred F = 9.50, P = 0.0033; mean-centred F = 10.09, P = 0.0026.
R prints the warning “Chi-squared approximation may be incorrect”
Cause: The table has expected counts below 5, so the chi-square approximation is unreliable. In the small example [[7,3],[2,8]], the expected counts are 4.5 and 5.5, and R prints this warning.
Fix: Use Fisher’s exact test. For this table, Fisher gives P = 0.070 and the corrected chi-square gives P = 0.072.
R’s chisq.test result differs from the uncorrected chi-square in the textbook rule
Cause: R and SciPy apply the Yates continuity correction to 2×2 tables by default; SPSS outputs both the corrected and uncorrected rows.
Fix: To report by the textbook rule, set correct = FALSE and check the conditions yourself. On the infert data: uncorrected χ² = 27.18, P = 1.8×10⁻⁷; corrected χ² = 25.79, P = 3.8×10⁻⁷.
P ≥ 0.05, and the paper says the two groups do not differ
Cause: Not statistically significant does not mean no difference (Altman and Bland 1995). In small samples, the interval often contains both clinically meaningful differences and zero.
Fix: Write “the difference was not statistically significant” and report the confidence interval. To show two groups are equivalent, use an equivalence or non-inferiority design.
The paper reports only P values, with no effect size or confidence interval
Cause: A P value does not show the size of a difference. For example, with the same P = 0.04, a mean difference of 0.5 mmHg and one of 15 mmHg have completely different clinical meanings.
Fix: For the primary outcome, report the effect estimate (mean difference, risk difference, OR, HR and so on) with its 95% CI, following the SAMPL guidelines.
A table reports “mean ± SE” to describe the variation in the data
Cause: The SE is an inferential statistic, roughly half the width of a 68% confidence interval. It does not describe the spread of the data.
Fix: For roughly normal data, write “mean (SD)”. For skewed data, give the median and interquartile range with its lower and upper bounds.
Ten cases per group, 20 outcomes compared, and one gives P < 0.05
Cause: Even if the drug does nothing, 20 tests are expected to produce one P < 0.05 by chance.
Fix: Name the primary outcome in the protocol. Report the others as exploratory, or correct for multiple comparisons.
The paper says “A causes B”, based only on a correlation coefficient
Cause: In observational data, a correlation may come from confounding.
Fix: Use “correlated” or “associated”, not “causes” or “affects”. To adjust for confounding, use multivariable regression and list the adjustment variables.
The correlation between two measurement methods is high, so the methods are taken to agree
Cause: Correlation only reflects a linear relation between two sets of readings. Two methods can correlate strongly yet differ systematically. Bland and Altman (1986) showed that correlation is misleading for judging agreement.
Fix: Compute the mean of the differences and the 95% limits of agreement (mean ±1.96 SD), which is the Bland-Altman method. The intraclass correlation coefficient (ICC) is another option.
Repeated measurements from the same subjects are pooled, and the correlation is very high
Cause: The sample size is overstated, and the correlation may reflect only differences between individuals.
Fix: Compute the within-subject and between-subject correlations separately (Bland and Altman, 1995, BMJ).
McNemar test P values differ between R and statsmodels
Cause: R’s mcnemar.test defaults to the continuity-corrected chi-square, while statsmodels’ mcnemar defaults to the exact binomial test. On the 1600-person data: corrected chi-square P = 4.1×10⁻⁵, exact P = 3.7×10⁻⁵.
Fix: Set both to the same method, and state the method used in the report.
R and SciPy give different OR values for Fisher’s test (8.15 vs 9.33)
Cause: R’s fisher.test gives the conditional maximum likelihood OR, while SciPy’s fisher_exact gives the sample OR (ad/bc). The two differ noticeably in small samples.
Fix: State how the OR was computed when reporting it, or estimate it consistently with logistic regression.
In repeated-measures ANOVA, Mauchly’s sphericity test gives P < 0.05
Cause: When sphericity fails, the uncorrected F test is unreliable. Measured on Indometh: Mauchly W = 0.00063, P = 0.0059.
Fix: Report the Greenhouse-Geisser or Huynh-Feldt corrected result, with the ε value. Measured here: GG ε = 0.378, corrected degrees of freedom 1.51 and 7.55, P = 4.7×10⁻⁶.
R’s confint(glm) gives a different OR interval from statsmodels and SPSS (2.24 to 5.19 vs 2.22 to 5.12)
Cause: R’s confint(glm) defaults to profile-likelihood intervals, while statsmodels and SPSS give Wald intervals. The two are close in large samples but differ in small samples or when OR is large.
Fix: For Wald intervals, use confint.default(glm) in R, and state the interval type in the report.
statsmodels PHReg coefficient differs from R coxph (−0.51256 vs −0.51322)
Cause: R and lifelines use the Efron method for tied event times by default; statsmodels’ PHReg uses the Breslow method by default.
Fix: Use the same tie method on both sides, or state the method in the report. Measured here, the two coefficients differ only slightly.
Only 30 events, but 10 predictors entered, and the coefficients are very unstable
Cause: Too few events per variable (EPV < 10) lead to seriously biased coefficient estimates.
Fix: Allow at least 10 events per predictor (EPV ≥ 10). Calculate sample size for prediction models by the method of Riley et al.
pingouin’s paired cohen_d is 0.83, not the dz of 1.28
Cause: The “paired Cohen d” has several definitions. pingouin divides by the average of the two measurement SDs; dz divides by the SD of the differences.
Fix: Give the formula in the paper, and state which definition was used.
R reports “unused argument (pooled_sd = FALSE)”
Cause: Both rstatix and effectsize define cohens_d. The package loaded later masks the other, and the arguments do not match.
Fix: Write effectsize::cohens_d to name the package explicitly.
The first import of pingouin takes a long time (about 80 seconds on this machine)
Cause: The first import builds a compilation cache.
Fix: Wait for it to finish. Later imports are normal.
R’s cor.test prints “Cannot compute exact p-value with ties”
Cause: With tied values in the data, the exact P value for Spearman correlation cannot be computed.
Fix: Add exact = FALSE to use the approximate method.
cor.test(aq_all$Ozone, aq_all$Temp, method = "spearman", exact = FALSE)The paired Wilcoxon P values differ between R and SciPy (0.0091 vs 0.0039)
Cause: With zero differences and ties, R uses a normal approximation with correction; SciPy 1.18 gives the exact P by default.
Fix: In SciPy, set method='approx', correction=True to match R.
Swapping the two factors in aov changes the P value of one main effect a lot (0.056 vs 4.9e-07)
Cause: R’s aov and statsmodels use type I (sequential) sums of squares by default. In unbalanced designs, the results change with the order of the variables.
Fix: Use car::Anova with type = 2 or type = 3 (type = 3 needs contr.sum), or statsmodels’ anova_lm(typ=3), and compare with SPSS’s default type III.
R aov, cylinders entered first (type I) P = 0.056
R aov, transmission entered first (type I) P = 4.9e-07
car::Anova type = 2 / pingouin P = 0.056
car::Anova type = 3 (contr.sum) P = 0.083
statsmodels anova_lm(typ=3) P = 0.083 # matches SPSS default type IIIThe first PC explains 98.3% of the variance, and almost all loadings come from one variable
Cause: Without standardization, the variable with the largest values dominates the variance. In the PBC data, alkaline phosphatase has loading −1.000.
Fix: Use prcomp(x, scale. = TRUE) in R, or StandardScaler before PCA in sklearn. After standardization, the first component explains 29.0%.
The first component loadings have opposite signs in R and Python
Cause: The sign of a principal component is arbitrary.
Fix: Read the relative directions between variables, not the absolute signs.
The SPSS component matrix values differ from the R prcomp rotation
Cause: The two are defined differently: R’s rotation holds eigenvectors, while SPSS’s component matrix holds loadings, that is, eigenvectors times the square root of the eigenvalues.
Fix: Convert rotation to loadings with loadings <- sweep(pca$rotation, 2, pca$sdev, "*"). To get the expression coefficients from the SPSS component matrix, divide each column by the square root of its eigenvalue. Verified here: rotation times sdev matches the loading matrix.
sklearn’s first eigenvalue is 2.622, not R’s 2.613
Cause: sklearn’s explained_variance_ divides by n−1, while StandardScaler standardizes with n, so the values differ slightly.
Fix: The proportions of variance explained are not affected. When comparing eigenvalues, use those of the correlation matrix (2.613 here).
The paper uses the difference between “standard drug + new drug” and “standard drug” to show the new drug works
Cause: The two drugs may interact, so the difference cannot be fully attributed to the new drug. For example, 24 mice were split into a control, standard drug A and A + new drug B.
Fix: Add a group with the new drug alone to form a 2×2 factorial design, and test both main effects and the interaction with two-way ANOVA.
Postoperative time points are analysed with a randomized block ANOVA
Cause: Time points cannot be randomized, and adjacent time points in the same patient are usually more strongly correlated, which breaks the randomized block assumptions. For example, 46 LASIK patients had visual fields measured before surgery and at 1 day, 1 month, 3 months and 6 months after.
Fix: Analyse it as a repeated-measures design, reporting the sphericity test and correction, or use a mixed model.
A tutorial says Tukey requires equal group sizes, so Tukey is dropped
Cause: This is not correct. With unequal group sizes, the Tukey-Kramer method applies, and R and SPSS handle it automatically.
Fix: With unequal group sizes, use TukeyHSD in R or the Tukey option in SPSS.
A tutorial says the SNK method controls the type I error
Cause: SNK controls the familywise error rate only when all group means are equal; it does not when only some are equal.
Fix: Journal reviewers often ask for Tukey or Holm instead.
References
- Lang T, Altman DG. SAMPL Guidelines (EQUATOR Network) — P value format, effect sizes with 95% CIs, mean (SD) format, SE not used for variability
- Delacre M, Lakens D, Leys C. Why psychologists should by default use Welch's t-test instead of Student's t-test. Int Rev Soc Psychol 2017 — Basis for Welch's t as the default; problems with choosing after a variance test
- Rochon J, Gondan M, Kieser M. To test or not to test: preliminary assessment of normality. BMC Med Res Methodol 2012 — The two-stage procedure of testing normality before choosing a t-test or rank test
- Lumley T, et al. The importance of the normality assumption in large public health data sets. Annu Rev Public Health 2002 — Robustness of t-tests and linear regression in large samples; "large enough" is often under 100
- Kim HY. Assessing normal distribution (2) using skewness and kurtosis. Restor Dent Endod 2013 — Skewness and kurtosis thresholds by sample size
- Hart A. Mann-Whitney test is not just a test of medians. BMJ 2001 — Interpreting Mann-Whitney results
- Bland JM, Altman DG. Multiple significance tests: the Bonferroni method. BMJ 1995 — False positives from multiple tests and the Bonferroni correction
- Bender R, Lange S. Adjusting for multiple testing—when and how? J Clin Epidemiol 2001 — When to adjust in confirmatory and exploratory studies
- Summary of the NEJM 2019 statistical reporting guidelines (Harrington et al.) — Secondary outcomes without pre-specified adjustment reported as estimates with 95% CIs
- Campbell I. Chi-squared and Fisher–Irwin tests of two-by-two tables with small sample recommendations. Stat Med 2007 — Choosing between the N−1 chi-squared and Fisher tests
- Bland JM, Altman DG. Statistical methods for assessing agreement between two methods of clinical measurement. Lancet 1986 — Correlation cannot assess agreement
- Bland JM, Altman DG. Statistics Notes index (University of York) — Correlation with repeated observations, Absence of evidence is not evidence of absence, and others
- Peduzzi P, et al. A simulation study of the number of events per variable in logistic regression analysis. J Clin Epidemiol 1996 — Source of EPV≥10
- What's new in IBM SPSS Statistics 27 — Effect sizes with confidence intervals for t-tests and one-way ANOVA from SPSS 27
- IBM SPSS tutorial: Independent-Samples T Test table — Meaning of the two rows in the SPSS independent-samples t-test
- SciPy documentation: scipy.stats.ttest_ind — equal_var defaults to True
- pingouin documentation: pingouin.ttest — Behavior of correction='auto'
- Practitioner post: Xiaobai Learns Statistics, "Common misuses of ANOVA in papers" (repost by Yikahui, CSDN, Chinese) — Review cases of a missing factorial group and repeated measures analyzed as randomized blocks
- Practitioner post: study notes on Practical Medical Statistics and SAS, comparing categorical data (CSDN, Chinese) — Chinese textbook rules for 2×2, paired and R×C chi-squared tests
- Practitioner post: SPSS steps for principal component analysis (CSDN, Chinese) — Dividing the SPSS component matrix by the square root of the eigenvalue
- Practitioner post: meaning and choice of pairwise multiple comparison methods in ANOVA (CSDN, Chinese) — Incorrect claims about Tukey and SNK in Chinese tutorials, corrected on this page