rstatix
rstatix wraps the base R tests so that each one takes a data frame and a formula and returns
a tibble. The result works with the pipe, with group_by(), and with ggpubr’s
stat_pvalue_manual(). Pairwise functions adjust their p-values with Holm’s method by
default. The examples run in rstatix 1.1.0.
Quick reference
Section titled “Quick reference”| Function | Test | When to use |
|---|---|---|
get_summary_stats() |
Descriptive statistics | Before any test |
shapiro_test() |
Shapiro-Wilk | Normality within each group |
levene_test() |
Levene | Equal variances across groups |
t_test() |
Welch or Student t-test | Two groups, or every pair |
pairwise_t_test() |
t-tests with a pooled SD | Every pair, as pairwise.t.test() |
wilcox_test() |
Wilcoxon rank-sum or signed-rank | Two groups, skewed data |
anova_test() |
ANOVA, including repeated measures | Three or more group means |
welch_anova_test() |
Welch ANOVA | Unequal variances |
kruskal_test() |
Kruskal-Wallis | Three or more groups, ranks |
friedman_test(y ~ x | id) |
Friedman | Repeated measures, ranks |
wilcox_test(paired = TRUE, id = ) |
Wilcoxon signed-rank | Post hoc after Friedman |
tukey_hsd() |
Tukey HSD | After ANOVA |
games_howell_test() |
Games-Howell | After Welch ANOVA |
dunn_test() |
Dunn | After Kruskal-Wallis |
cohens_d() |
Cohen’s d | Effect size for two means |
cor_test() |
Pearson, Spearman, Kendall | Two numeric columns |
chisq_test(), fisher_test() |
Chi-square, Fisher | Contingency tables |
mcnemar_test() |
McNemar | Paired 2 by 2 table |
adjust_pvalue() |
Multiple testing correction | Holm, BH, Bonferroni |
add_significance() |
Stars from p-values | Labels for plots and tables |
add_xy_position() |
Bracket coordinates | Input to stat_pvalue_manual() |
The table holds one gene measured in 20 samples per treatment arm, split over two batches, with a viability readout that falls as expression rises.
library(rstatix)library(dplyr)library(ggpubr)
set.seed(42)dir.create("outputs", showWarnings = FALSE)options(width = 90)
experiment <- tibble( sample_id = sprintf("S%02d", 1:60), group = factor(rep(c("Control", "Drug_A", "Drug_B"), each = 20)), batch = factor(rep(rep(c("Batch1", "Batch2"), each = 10), 3)), expression = c(rnorm(20, 10, 1.5), rnorm(20, 13, 2), rnorm(20, 11.5, 1.5))) |> mutate(viability = 110 - 3 * expression + rnorm(60, 0, 4))print(experiment, n = 3)# A tibble: 60 × 5 sample_id group batch expression viability <chr> <fct> <fct> <dbl> <dbl>1 S01 Control Batch1 12.1 72.42 S02 Control Batch1 9.15 83.33 S03 Control Batch1 10.5 80.7# ℹ 57 more rowsSummary statistics
Section titled “Summary statistics”get_summary_stats() respects group_by(). type picks the set of columns, such as
"mean_sd", "median_iqr", or "full".
experiment |> group_by(group) |> get_summary_stats(expression, type = "mean_sd")# A tibble: 3 × 5 group variable n mean sd <fct> <fct> <dbl> <dbl> <dbl>1 Control expression 20 10.3 1.972 Drug_A expression 20 12.5 2.223 Drug_B expression 20 11.5 1.54Check the assumptions
Section titled “Check the assumptions”Shapiro-Wilk tests normality within each group. A p-value above 0.05 means the test found no evidence against normality, which with 20 samples is weak evidence for it.
experiment |> group_by(group) |> shapiro_test(expression)# A tibble: 3 × 4 group variable statistic p <fct> <chr> <dbl> <dbl>1 Control expression 0.944 0.2852 Drug_A expression 0.980 0.9303 Drug_B expression 0.910 0.0647Levene’s test compares the variances across groups. A significant result points to Welch’s ANOVA and the Games-Howell post hoc test below.
experiment |> levene_test(expression ~ group)# A tibble: 1 × 4 df1 df2 statistic p <int> <int> <dbl> <dbl>1 2 57 1.42 0.250t-test
Section titled “t-test”With more than two groups, t_test() runs every pair and adds p.adj. It runs Welch’s test
unless you set var.equal = TRUE.
experiment |> t_test(expression ~ group)# A tibble: 3 × 10 .y. group1 group2 n1 n2 statistic df p p.adj p.adj.signif* <chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl> <dbl> <chr>1 expression Control Drug_A 20 20 -3.27 37.5 0.00230 0.00691 **2 expression Control Drug_B 20 20 -2.17 35.9 0.0368 0.0736 ns3 expression Drug_A Drug_B 20 20 1.59 33.8 0.121 0.121 nsref.group compares each group with one reference, so fewer tests share the adjustment.
effect.size = TRUE adds Cohen’s d for each pair.
experiment |> t_test(expression ~ group, ref.group = "Control", effect.size = TRUE) |> select(group1, group2, statistic, p.adj, cohens.d, magnitude)# A tibble: 2 × 6 group1 group2 statistic p.adj cohens.d magnitude <chr> <chr> <dbl> <dbl> <dbl> <ord>1 Control Drug_A -3.27 0.00461 -1.03 large2 Control Drug_B -2.17 0.0368 -0.686 moderatePairwise t-tests with a pooled SD
Section titled “Pairwise t-tests with a pooled SD”pairwise_t_test() reproduces base R’s pairwise.t.test(). It pools the standard deviation
of all groups, so each test has more degrees of freedom than t_test(), which uses only the
two groups in a pair. Set pool.sd = FALSE to get separate Welch tests. Control against
Drug_A gives p = 0.00076 here, against 0.0023 from the Welch test in t_test(). As in
compare_means(), p.signif comes from the raw p-value, so read p.adj.signif.
experiment |> pairwise_t_test(expression ~ group, p.adjust.method = "holm")# A tibble: 3 × 9 .y. group1 group2 n1 n2 p p.signif p.adj p.adj.signif* <chr> <chr> <chr> <int> <int> <dbl> <chr> <dbl> <chr>1 expression Control Drug_A 20 20 0.000760 *** 0.00228 **2 expression Control Drug_B 20 20 0.0519 ns 0.104 ns3 expression Drug_A Drug_B 20 20 0.121 ns 0.121 nsPaired t-test
Section titled “Paired t-test”Pass the subject column as id. The test then matches the two measurements of each patient
by name instead of by row order, and drops a patient who has only one of them.
baseline <- rnorm(12, 9, 1.5)paired <- tibble( patient = rep(sprintf("P%02d", 1:12), times = 2), time = factor(rep(c("Baseline", "Week4"), each = 12)), expression = c(baseline, baseline + rnorm(12, 1, 0.8)))
paired |> t_test(expression ~ time, paired = TRUE, id = "patient")# A tibble: 1 × 8 .y. group1 group2 n1 n2 statistic df p* <chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl>1 expression Baseline Week4 12 12 -5.57 11 0.000169Wilcoxon test
Section titled “Wilcoxon test”wilcox_test() runs the rank-based test for two groups. With three groups it runs every
pair, as t_test() does.
experiment |> wilcox_test(expression ~ group)# A tibble: 3 × 9 .y. group1 group2 n1 n2 statistic p p.adj p.adj.signif* <chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl> <chr>1 expression Control Drug_A 20 20 99 0.00562 0.0169 *2 expression Control Drug_B 20 20 123 0.0375 0.0750 ns3 expression Drug_A Drug_B 20 20 257 0.127 0.127 nsOne-way ANOVA
Section titled “One-way ANOVA”anova_test() reports generalized eta squared, ges, as the effect size.
expression_aov <- experiment |> anova_test(expression ~ group)expression_aovANOVA Table (type II tests)
Effect DFn DFd F p p<.05 ges1 group 2 57 6.359 0.003 * 0.182When Levene’s test fails, use Welch’s ANOVA, which does not assume equal variances.
experiment |> welch_anova_test(expression ~ group)# A tibble: 1 × 7 .y. n statistic DFn DFd p method* <chr> <int> <dbl> <dbl> <dbl> <dbl> <chr>1 expression 60 5.4 2 37.1 0.009 Welch ANOVATwo-way ANOVA
Section titled “Two-way ANOVA”* fits both main effects and their interaction. The default sums of squares are type II.
experiment |> anova_test(expression ~ group * batch)ANOVA Table (type II tests)
Effect DFn DFd F p p<.05 ges1 group 2 54 6.211 0.004 * 0.1872 batch 1 54 0.833 0.365 0.0153 group:batch 2 54 0.422 0.658 0.015Repeated measures ANOVA
Section titled “Repeated measures ANOVA”Give the outcome as dv, the subject as wid, and the repeated factor as within.
get_anova_table() applies the Greenhouse-Geisser correction when Mauchly’s test finds that
sphericity fails. Here sphericity holds, so the table keeps the uncorrected 2 and 38 degrees
of freedom.
tumor <- tibble( patient = rep(sprintf("P%02d", 1:20), times = 3), time = factor(rep(c("Baseline", "Month3", "Month6"), each = 20)), tumor_mm = c(rnorm(20, 50, 10), rnorm(20, 42, 9), rnorm(20, 36, 8)))
tumor |> anova_test(dv = tumor_mm, wid = patient, within = time) |> get_anova_table()ANOVA Table (type III tests)
Effect DFn DFd F p p<.05 ges1 time 2 38 8.086 0.001 * 0.26Friedman test
Section titled “Friedman test”The rank-based test for repeated measures on the same subjects. The formula names the
subject after |.
tumor |> friedman_test(tumor_mm ~ time | patient)# A tibble: 1 × 6 .y. n statistic df p method* <chr> <int> <dbl> <dbl> <dbl> <chr>1 tumor_mm 20 7.3 2 0.0260 Friedman testPaired Wilcoxon post hoc test
Section titled “Paired Wilcoxon post hoc test”After a significant Friedman test, compare the time points two at a time with a paired
Wilcoxon signed-rank test. id pairs the rows by patient, and the p-values get the Holm
adjustment.
tumor |> wilcox_test(tumor_mm ~ time, paired = TRUE, id = "patient") |> select(group1, group2, n1, statistic, p, p.adj, p.adj.signif)# A tibble: 3 × 7 group1 group2 n1 statistic p p.adj p.adj.signif <chr> <chr> <int> <dbl> <dbl> <dbl> <chr>1 Baseline Month3 20 138 0.231 0.231 ns2 Baseline Month6 20 188 0.00102 0.00305 **3 Month3 Month6 20 156 0.0583 0.117 nsKruskal-Wallis test
Section titled “Kruskal-Wallis test”kruskal_test() is the rank-based alternative to one-way ANOVA. kruskal_effsize() gives
the matching effect size.
experiment |> kruskal_test(expression ~ group)# A tibble: 1 × 6 .y. n statistic df p method* <chr> <int> <dbl> <int> <dbl> <chr>1 expression 60 9.35 2 0.00932 Kruskal-Wallisexperiment |> kruskal_effsize(expression ~ group)# A tibble: 1 × 5 .y. n effsize method magnitude* <chr> <int> <dbl> <chr> <ord>1 expression 60 0.129 eta2[H] moderatePost hoc tests
Section titled “Post hoc tests”Tukey’s HSD follows a one-way ANOVA with equal variances.
experiment |> tukey_hsd(expression ~ group)# A tibble: 3 × 9 term group1 group2 null.value estimate conf.low conf.high p.adj p.adj.signif* <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>1 group Control Drug_A 0 2.17 0.702 3.64 0.00216 **2 group Control Drug_B 0 1.21 -0.257 2.68 0.125 ns3 group Drug_A Drug_B 0 -0.959 -2.43 0.508 0.266 nsGames-Howell follows Welch’s ANOVA.
experiment |> games_howell_test(expression ~ group)# A tibble: 3 × 8 .y. group1 group2 estimate conf.low conf.high p.adj p.adj.signif* <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr>1 expression Control Drug_A 2.17 0.551 3.79 0.00637 **2 expression Control Drug_B 1.21 -0.154 2.58 0.0905 ns3 expression Drug_A Drug_B -0.959 -2.44 0.520 0.264 nsDunn’s test follows Kruskal-Wallis.
experiment |> dunn_test(expression ~ group)# A tibble: 3 × 9 .y. group1 group2 n1 n2 statistic p p.adj p.adj.signif* <chr> <chr> <chr> <int> <int> <dbl> <dbl> <dbl> <chr>1 expression Control Drug_A 20 20 3.04 0.00235 0.00705 **2 expression Control Drug_B 20 20 1.79 0.0730 0.146 ns3 expression Drug_A Drug_B 20 20 -1.25 0.212 0.212 nsEffect size
Section titled “Effect size”Cohen’s d is the difference in means in units of standard deviation. The magnitude labels use 0.2, 0.5, and 0.8 as the cut points for small, moderate, and large.
experiment |> cohens_d(expression ~ group)# A tibble: 3 × 7 .y. group1 group2 effsize n1 n2 magnitude* <chr> <chr> <chr> <dbl> <int> <int> <ord>1 expression Control Drug_A -1.03 20 20 large2 expression Control Drug_B -0.686 20 20 moderate3 expression Drug_A Drug_B 0.503 20 20 moderateCorrelation
Section titled “Correlation”cor_test() takes bare column names and returns the coefficient with its confidence
interval. Use method = "spearman" for a rank correlation.
experiment |> cor_test(expression, viability, method = "pearson")# A tibble: 1 × 9 var1 var2 cor statistic df p conf.low conf.high method <chr> <chr> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>1 expression viability -0.87 -13.1 58 4.79e-19 -0.918 -0.784 PearsonCategorical data
Section titled “Categorical data”chisq_test() and fisher_test() take a contingency table. Fisher’s exact test suits small
counts, where the chi-square approximation fails.
responders <- matrix( c(14, 6, 7, 13), nrow = 2, dimnames = list(genotype = c("WT", "Mutant"), response = c("Yes", "No")))responders responsegenotype Yes No WT 14 7 Mutant 6 13chisq_test(responders)# A tibble: 1 × 6 n statistic p df method p.signif* <dbl> <dbl> <dbl> <int> <chr> <chr>1 40 3.61 0.0575 1 Chi-square test nsfisher_test(responders, detailed = TRUE)# A tibble: 1 × 8 n estimate p conf.low conf.high method alternative p.signif* <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr> <chr>1 40 4.16 0.0562 0.969 20.2 Fisher's Exact test two.sided nsMcNemar test for paired outcomes
Section titled “McNemar test for paired outcomes”When the same patients are classified twice, for example a biomarker before and after
treatment, the 2 by 2 table is paired and the chi-square test does not apply. McNemar’s test
uses only the discordant cells, here 12 patients who turned negative and 3 who turned
positive. It applies a continuity correction by default; correct = FALSE turns it off.
biomarker <- matrix( c(20, 3, 12, 15), nrow = 2, dimnames = list( before = c("Positive", "Negative"), after = c("Positive", "Negative") ))biomarker afterbefore Positive Negative Positive 20 12 Negative 3 15mcnemar_test(biomarker)# A tibble: 1 × 6 n statistic df p p.signif method* <dbl> <dbl> <dbl> <dbl> <chr> <chr>1 50 4.27 1 0.0389 * McNemar testGrouped tests
Section titled “Grouped tests”group_by() runs the test once per level, here once per batch. The p-values are adjusted
within each batch.
experiment |> group_by(batch) |> t_test(expression ~ group, ref.group = "Control") |> select(batch, group1, group2, statistic, p, p.adj, p.adj.signif)# A tibble: 4 × 7 batch group1 group2 statistic p p.adj p.adj.signif <fct> <chr> <chr> <dbl> <dbl> <dbl> <chr>1 Batch1 Control Drug_A -2.19 0.0460 0.0919 ns2 Batch1 Control Drug_B -1.14 0.270 0.270 ns3 Batch2 Control Drug_A -2.40 0.0273 0.0545 ns4 Batch2 Control Drug_B -1.84 0.0837 0.0837 nsAdjust and format p-values
Section titled “Adjust and format p-values”adjust_pvalue() corrects a column of p-values across all rows. Here the tests run without
an adjustment, then all six p-values from both batches share one Benjamini-Hochberg
correction. add_significance() turns a p-value column into stars.
experiment |> group_by(batch) |> t_test(expression ~ group, p.adjust.method = "none") |> adjust_pvalue(method = "BH") |> add_significance("p.adj") |> select(batch, group1, group2, p, p.adj, p.adj.signif)# A tibble: 6 × 6 batch group1 group2 p p.adj p.adj.signif <fct> <chr> <chr> <dbl> <dbl> <chr>1 Batch1 Control Drug_A 0.0460 0.138 ns2 Batch1 Control Drug_B 0.270 0.324 ns3 Batch1 Drug_A Drug_B 0.183 0.274 ns4 Batch2 Control Drug_A 0.0273 0.138 ns5 Batch2 Control Drug_B 0.0837 0.167 ns6 Batch2 Drug_A Drug_B 0.424 0.424 nsBrackets on a ggpubr plot
Section titled “Brackets on a ggpubr plot”add_xy_position() adds the bracket positions, xmin, xmax, and y.position, that
stat_pvalue_manual() reads. Raise step.increase when the stacked brackets touch their
labels. get_test_label() and get_pwc_label() write the overall test and the pairwise
method into the subtitle and the caption.
pwc <- experiment |> t_test(expression ~ group) |> add_xy_position(x = "group", step.increase = 0.25)
pwc_plot <- ggboxplot( experiment, x = "group", y = "expression", fill = "group", palette = "npg", add = "jitter") + stat_pvalue_manual(pwc, label = "p.adj.signif", tip.length = 0.01) + labs( x = NULL, y = "Expression, log2 CPM", subtitle = get_test_label(expression_aov, detailed = TRUE), caption = get_pwc_label(pwc) ) + theme(legend.position = "none")
ggsave( "outputs/rstatix-pvalue-brackets.png", pwc_plot, width = 6, height = 5.5, dpi = 150, bg = "white")
See also
Section titled “See also”- Two Groups: t-test and Wilcoxon and Multiple Groups: ANOVA and Kruskal-Wallis explain when each test fits.
- Checking Assumptions covers normality and equal variance in depth.
- Mixed-Effects and Repeated Measures models repeated measures with random effects for each subject.
- Categorical Data: Chi-square and Fisher and Multiple Testing Correction cover the last two sections of this page.
- The ggpubr cheatsheet draws the plots that take these tables.
Scientific references
Section titled “Scientific references”The rstatix package by Kassambara supplies pipe-friendly functions for basic statistical tests.
Further reading
Section titled “Further reading”-
The reference distinguishes paired tests, pooled variance, pairwise comparisons and adjustment within groups.