Custom contrasts in R: contrast coefficient matrix or contrast matrix / coding scheme? And how to get there?

杀马特。学长 韩版系。学妹 提交于 2019-12-03 06:52:21

Claim 2 is correct (see the answers here and here) and sometimes claim 1, too. This is because there are cases in which the generalized inverse of the (transposed) coefficient matrix is equal to the matrix itself.

For what it's worth....

If you have a factor with 3 levels (levels A, B, and C) and you want to test the following orthogonal contrasts: A vs B, and the avg. of A and B vs C, your contrast codes would be:

Cont1<- c(1,-1, 0)
Cont2<- c(.5,.5, -1)

If you do as directed on the UCLA site (transform coefficients to make a coding scheme), as such:

Contrasts(Variable)<- solve(t(cbind(c(1,1,1), Cont1, Cont2)))[,2:3]

then your results are IDENTICAL to if you had created two dummy variables (e.g.:

Dummy1<- ifelse(Variable=="A", 1, ifelse(Variable=="B", -1, 0))
Dummy2<- ifelse(Variable=="A", .5, ifelse(Variable=="B", .5, -1))

and entered them both into the regression equation instead of your factor, which makes me inclined to think that this is the correct way.

PS I don't write the most elegant R code, but it gets the job done. Sorry, I'm sure there are easier ways to recode variables, but you get the gist.

I'm probably missing something, but in each of your three examples, you specify the contrast matrix in the same way, i.e.

## Note it should plural of contrast
contrasts(myFactor) = x

The only thing that differs is the value of x.

Using the data from the UCLA website as an example

hsb2 = read.table('http://www.ats.ucla.edu/stat/data/hsb2.csv', header=T, sep=",")

#creating the factor variable race.f
hsb2$race.f = factor(hsb2$race, labels=c("Hispanic", "Asian", "African-Am", "Caucasian"))

We can specify either the treatment version of the contrasts

contrasts(hsb2$race.f) = contr.treatment(4)
summary(lm(write ~ race.f, hsb2))

or the sum version

contrasts(hsb2$race.f) = contr.sum(4)
summary(lm(write ~ race.f, hsb2))

Alternatively, we can specify a bespoke contrast matrix.

See ?contr.sum for other standard contrasts.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!