[R] Understanding custom contrasts

Sandy Miller
Sun, 06 May 2012 15:59:20 -0000

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