[R] defining contrasts in lm() - is there a simpler way?

Mark Heckmann mark.heckmann at gmx.de
Tue Dec 14 22:58:08 CET 2010

Dear R users,

I am looking for a simple way to define a contrast in a linear model. 
I have a data frame with two factors (f1, f2) and a dependent y.

x <- data.frame(y =rnorm(30), f1=gl(2, 15), f2=gl(3, 5, 30))

Now I want to specify the following contrast:   "f1= 1 or 2 and f2=1" vs. "f1= 1 or 2 and f2=3" 
The best I can come up with is the following:

x$new[x$f1==1 & x$f2==1] <- 1
x$new[x$f1==1 & x$f2==2] <- 2
x$new[x$f1==1 & x$f2==3] <- 3
x$new[x$f1==2 & x$f2==1] <- 4
x$new[x$f1==2 & x$f2==2] <- 5
x$new[x$f1==2 & x$f2==3] <- 6
x$new <- as.factor(x$new)
contrasts(x$new) <- cbind(" my constrast" = c( .5, -.5,  0, .5, 0, -.5))
summary(lm(y ~ new, x))

I have two questions concerning this: 

1) if I take a look at the constrast matrix derived from the one
contrast I specified, I assume that R automatically adds the missing constrasts so they are orthogonal.

   round(cor(attributes(x$new)$contrast), 1)

Is that always the case?

2) Can I get this in a simpler way? I find it a bit tedious to define the constrast like above. 
Is there something simpler, like:

   lm(y ~ f1:f2, + "user defined contrast definition inside lm that is equivalent to the above")

Thanks in advance,
Mark Heckmann
Blog: www.markheckmann.de
R-Blog: http://ryouready.wordpress.com

More information about the R-help mailing list