[R] Understanding custom contrasts
Sandy Miller
kaesezeh at gmail.com
Sun May 6 17:59:20 CEST 2012
I have a question regarding customising contrasts for linear models I
read the section in Fox/Weisberg's CAR (2nd ed.) and was
thinking--apparently erroneously--that the following two snippets
would do the same:
# approach 1: default treatment contrasts
# generate data
set.seed(1111)
y <- c(rnorm(1000, -1), rnorm(1000, 0), rnorm(1000, 1))
x <- factor(rep(letters[1:3], each=1000))
# trying to get tests of b against a and b against c
x <- relevel(x, "b"); contrasts(x)
tapply(y, x, mean)
summary(lm(y~x))
# approach 2: custom contrasts
# generate same data
set.seed(1111)
y <- c(rnorm(1000, -1), rnorm(1000, 0), rnorm(1000, 1))
x <- factor(rep(letters[1:3], each=1000))
con <- matrix(c(1, -1, 0, 0, 1, -1), ncol=2); colnames(con) <- c("a vs
b", "b vs c")
contrasts(x) <- con
tapply(y, x, mean)
summary(lm(y~x))
Why is the result not the same, what am I doing wrong? Any help would
be much appreciated.
S
More information about the R-help
mailing list