Mark Heckmann
2010-Dec-14 21:58 UTC
[R] defining contrasts in lm() - is there a simpler way?
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 ??????????????????????????????????????? Mark Heckmann Blog: www.markheckmann.de R-Blog: http://ryouready.wordpress.com
Maybe Matching Threads
- using regular expressions to retrieve a digit-digit-dot structure from a string
- Flattening lists and environments (was: "how to flatten a list to the same level?")
- Defining origin for rotation in RGL device
- no partial matching of argument names after dots argument - why?
- blank space escape sequence in R?