Link Search Menu Expand Document (external link)

How to perform pairwise comparisons (in R)

See all solutions.

Task

When analyzing data from a completely randomized single-factor design, suppose that you have performed an ANOVA and noticed that there’s a significant difference between at least one pair of treatment levels. How can pairwise comparisons help us explore which pairs of treatment levels are different?

Related tasks:

Solution

The solution below uses an example dataset that details the counts of insects in an agricultural experiment with six types of insecticides, labeled A through F. (This is one of the datasets built into R for use in examples like this one.)

1
2
df <- InsectSprays
head( df, 10 )
1
2
3
4
5
6
7
8
9
10
11
   count spray
1  10    A    
2   7    A    
3  20    A    
4  14    A    
5  14    A    
6  12    A    
7  10    A    
8  23    A    
9  17    A    
10 20    A    

Before we perform any post hoc analysis, we need to see if the count of insects depends on the type of insecticide given by conducting a one way ANOVA. (See also how to do a one-way analysis of variance (ANOVA).)

1
2
aov1 = aov(count ~ spray, data = df)
summary(aov1)
1
2
3
4
5
            Df Sum Sq Mean Sq F value Pr(>F)    
spray        5   2669   533.8    34.7 <2e-16 ***
Residuals   66   1015    15.4                   
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

At the 5% significance level, we see that the count differs according to the type of insecticide used. We assume that the model assumptions are met, but do not verify that here.

If we would like to compare the pairs without any corrections, we can use the pairwise.t.test function built into R.

1
pairwise.t.test(df$count, df$spray, p.adj="none")
1
2
3
4
5
6
7
8
9
10
11
12
	Pairwise comparisons using t tests with pooled SD 

data:  df$count and df$spray 

  A       B       C       D       E      
B 0.604   -       -       -       -      
C 7.3e-11 8.5e-12 -       -       -      
D 9.8e-08 1.2e-08 0.081   -       -      
E 2.8e-09 3.3e-10 0.379   0.379   -      
F 0.181   0.408   2.8e-13 4.0e-10 1.1e-11

P value adjustment method: none 

Techniques to adjust the above table for multiple comparisons include the Bonferroni correction, Fisher’s Least Significant Difference (LSD) method, Dunnett’s procedure, and Scheffe’s method. These can be used in place of “none” for the p.adj argument; see details here.

You can also determine the magnitude of these differences; see how to perform post-hoc analysis with Tukey’s HSD test.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Krtin Juneja (KJUNEJA@falcon.bentley.edu)