Skip to content

Instantly share code, notes, and snippets.

@bbolker
Last active April 8, 2022 01:06
Show Gist options
  • Select an option

  • Save bbolker/d3e23d1fa77a1d494aab5252077ad6fd to your computer and use it in GitHub Desktop.

Select an option

Save bbolker/d3e23d1fa77a1d494aab5252077ad6fd to your computer and use it in GitHub Desktop.
contrast example
dd <- data.frame(A = factor(c(1,2,2,2)),
B = factor(1:4),
y = 1:4)
dd$i <- with(dd, factor(sprintf("A%d.B%d",A,B)))
## set up *inverse* contrast matrix
invc <- matrix(c(
1/2, 1/6, 1/6, 1/6, ## A-weighted mean
-1, 1/3, 1/3, 1/3, ## A1 vs A2 (== B1 vs mean{B2, B3, B4})
0, 2/3, -1/3, -1/3, ## B2 vs mean(B2, B3, B4)
0, -1/3, 2/3, -1/3), ## B3 vs mean(B2, B3, B4)
nrow = 4, byrow = 4,
dimnames = list(c("int", "B.vs.A", "A1.vs.B2bar", "A2.vs.B2bar"),
dd$i))
print(invc, digits = 3)
## A1.B1 A2.B2 A2.B3 A2.B4
## int 0.5 0.167 0.167 0.167
## B.vs.A -1.0 0.333 0.333 0.333
## A1.vs.B2bar 0.0 0.667 -0.333 -0.333
## A2.vs.B2bar 0.0 -0.333 0.667 -0.333
## contrast matrix
zapsmall(solve(invc))
## int B.vs.A A1.vs.B2bar A2.vs.B2bar
## A1.B1 1 -0.5 0 0
## A2.B2 1 0.5 1 0
## A2.B3 1 0.5 0 1
## A2.B4 1 0.5 -1 -1
contrasts(dd$i) <- solve(invc)[,-1] ## drop intercept
## (or could use -1 or +0 in the formula)
zapsmall(coef(lm(y~i, dd)))
## (Intercept) iB.vs.A iA1.vs.B2bar iA2.vs.B2bar
## 2 2 -1 0
## (numbers check out with hand calculation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment