使用したいマトリックスを作成し、それをcontrasts
引数に設定するかlm
、因子自体のデフォルトのコントラストを設定することで、コントラストを好きなように設定できます。
いくつかのサンプルデータ:
set.seed(6)
d <- data.frame(g=gl(3,5,labels=letters[1:3]), x=round(rnorm(15,50,20)))
あなたが念頭に置いているコントラスト:
mycontrasts <- matrix(c(0,0,1,0,1,1), byrow=TRUE, nrow=3)
colnames(mycontrasts) <- c("12","23")
mycontrasts
# 12 23
#[1,] 0 0
#[2,] 1 0
#[3,] 1 1
次に、lm
呼び出しでこれを使用します。
> lm(x ~ g, data=d, contrasts=list(g=mycontrasts))
Call:
lm(formula = x ~ g, data = d, contrasts = list(g = mycontrasts))
Coefficients:
(Intercept) g12 g23
58.8 -13.6 5.8
手段を比較することで、それが正しいことを行うことを確認できます。
> diff(tapply(d$x, d$g, mean))
b c
-13.6 5.8
デフォルトのコントラストは、最初のレベルをベースラインとして使用することです:
> lm(x ~ g, data=d)
Call:
lm(formula = x ~ g, data = d)
Coefficients:
(Intercept) gb gc
58.8 -13.6 -7.8
contrasts
ただし、これは次のコマンドで変更できます。
> contrasts(d$g) <- mycontrasts
> lm(x ~ g, data=d)
Call:
lm(formula = x ~ g, data = d)
Coefficients:
(Intercept) g12 g23
58.8 -13.6 5.8