rregressionlsmeans

Estimating difference in lsmeans


How does one use lsmeans to estimate the difference in two pairwise contrasts? For instance--imagine a continuous dv and two factor predictors

library(lsmeans)
library(tidyverse)

dat <- data.frame(
  y = runif(30),
  x1 = 1:2 %>% 
    factor %>% 
    sample(30, T),
  x2 = letters[1:3] %>%
    factor %>% 
    sample(30, T)
  )

lm1 <- lm(y ~ x1 * x2, data = dat)

This call gets me the estimates of the effect of x1 by x2

lsmeans(lm1, ~ x1 | x2) %>% 
  pairs 

returns

x2 = a:
 contrast     estimate        SE df t.ratio p.value
 1 - 2    -0.150437681 0.2688707 24  -0.560  0.5810

x2 = b:
 contrast     estimate        SE df t.ratio p.value
 1 - 2    -0.048950972 0.1928172 24  -0.254  0.8018

x2 = c:
 contrast     estimate        SE df t.ratio p.value
 1 - 2    -0.006819473 0.2125610 24  -0.032  0.9747

This is fine, but I now want the difference of these contrasts, to see if these 1 - 2 differences are themselves different according to x2 levels.


Solution

  • Use

    lsm = lsmeans(lm1, ~ x1 * x2)
    contrast(lsm, interaction = “pairwise”)