1

I would like to use contrast() with an lsmeans object to perform some specific planned comparisons, but I cannot find a method to perform the comparisons I want. I want to compare whether one factor has an effect at either of two factor levels. For example, in the below I would like to compare whether A,C differs to B,C, and whether A,D is different to B,D. I do not want to compare whether A, C is different to B, D or different to A, D, etc.

fac_one <- c(rep("A", 200), rep ("B", 200))
fac_two <- rep(c("C", "D"), 200)

dats <- data.frame(fac_one= c(rep("A", 200), rep ("B", 200)),
                   fac_two= rep(c("C", "D"), 200))

dats$y <- NA

dats$y[dats$fac_one=="A" & dats$fac_two=="C"] <- 
  rnorm(100, mean=0.9, sd=1)
dats$y[dats$fac_one=="B" & dats$fac_two=="C"] <- 
  rnorm(100, mean=0.9, sd=1)

dats$y[dats$fac_one=="A" & dats$fac_two=="D"] <- 
  rnorm(100, mean=0.6, sd=1)
dats$y[dats$fac_one=="B" & dats$fac_two=="D"] <- 
  rnorm(100, mean=1.4, sd=1)

mod <- lm(y ~ fac_one*fac_two, data = dats)
Anova(mod)

lsmns <- lsmeans(mod, ~fac_one*fac_two)
#currently does many contrasts that I do not want to do
contrast(lsmns)

Thanks!

2 Answers2

2
contrast(lsmns, “pairwise”, by = “fac_two”)

It’s in the documentation

Russ Lenth
  • 5,922
  • 2
  • 13
  • 21
1

You can use | instead of * to tell emmeans to separate them into groups based on that factor. You can then use pairs to get pairwise comparisons within each group. Also note that both the package and the function have been renamed in the latest versions to emmeans from lsmeans, though this functionality is in the older versions as well.

> library(emmeans)
> lsmns <- emmeans(mod, ~fac_one|fac_two)
> pairs(lsmns)
fac_two = C:
 contrast estimate    SE  df t.ratio p.value
 A - B      -0.044 0.142 396 -0.309  0.7574 

fac_two = D:
 contrast estimate    SE  df t.ratio p.value
 A - B      -0.974 0.142 396 -6.848  <.0001 

PS. Nice reproducible example. :)

Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142