Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 781
tomw Avatar asked Feb 12 '26 06:02

tomw


2 Answers

Use

lsm = lsmeans(lm1, ~ x1 * x2)
contrast(lsm, interaction = “pairwise”)
like image 122
Russ Lenth Avatar answered Feb 14 '26 03:02

Russ Lenth


As I understand your problem right, you can use this solution :

lm1 <- lm(y ~ x1 * x2, data = dat)
means.int <- lsmeans(lm1, ~x1 + x2)
dd <- contrast(means.int, list(`a--b` = c(1,-1,-1,1,0,0), 
                               `a--c`=c(1,-1,0,0,-1,1),
                               `b--c` = c(0,0,1,-1,-1,1)), 
               adjust = 'mvt')
like image 37
Alex Avatar answered Feb 14 '26 03:02

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!