Search code examples
rcontrast

Contrasts for lm using contrast package


I'm using contrast package to construct contrasts for lm in R. With the following code I'm making contrast between Trt1 and Trt3.

Y <- c(10, 12, 14, 16, 9, 8)
Trt <- gl(n=3, k=2, length=3*2)
Data1 <- data.frame(Y, Trt)

Data1.lm <- lm(Y~Trt, data = Data1)

library(contrast)
Contrs1 <- contrast(Data1.lm, a=list(Trt="1"), b=list(Trt="3"), type = "average")
print(Contrs1, X=TRUE)

I'd like to make a contrast between the average of (Trt1 and Trt2) and Trt3. I used this code

Contrs2 <- contrast(Data1.lm, a=list(Trt="1", Trt="2"), b=list(Trt="3"), type = "average")
print(Contrs2, X=TRUE)

lm model parameter contrast

  Contrast     S.E.    Lower    Upper    t df Pr(>|t|)
1      6.5 1.224745 2.602315 10.39768 5.31  3   0.0131

Contrast coefficients:
  (Intercept) Trt2 Trt3
1           0    1   -1

I can see that this is not the desired contrast. I wonder how to get the correct contrast with the contrast package in R.

P.S. I know to do use the contrast matrix for aov function in R but for this particular problem I want to use contrast package.


Solution

  • You should specify the included treatment levels as a vector (Trt=c("1","2")), not a list. I figured this out by looking at the examples in ?contrast.lm (although admittedly it helps to know what you're looking for):

    Contrs2 <- contrast(Data1.lm, a=list(Trt=c("1","2")), b=list(Trt="3"),
                        type = "average")
    print(Contrs2, X=TRUE)
    ## lm model parameter contrast
    ##   Contrast    S.E.    Lower    Upper    t df Pr(>|t|)
    ## 1      4.5 1.06066 1.124506 7.875494 4.24  3    0.024