I want to fit a linear model for goal differences of ice hockey matches with regressor - difference in forms of teams. So my model has form:
$y_{ijt} = \mu + \alpha_i - \alpha_j + \varepsilon_{ijt}, (ij) = 1, \ldots,n$
where $\alpha$ denotes categorical variable with levels teams and $\mu$ home advantage. Notice that $(ij)$ determines only one match (two different teams). Is there an efficient way how to estimate $\alpha$ with contrasts "contr.sum" in R?
I have achieved it only in a very clumsy way using model.matrix. Suppose we have 3 teams a, b and c and the following data:
n <- 5
testFrame <- data.frame(home = rep(letters[1:3],
each = n),
guest =rep(letters[1:3][c(2, 3,
1)],
each = n),
y = c(rnorm(n), rnorm(n, 1),
rnorm(n)))
I have fitted lm
model with the last form set to 0 and then recalculated it to get $\alpha$.
dmatrix <- model.matrix(~ -1 + testFrame[, 1]) -
model.matrix(~ -1 +
testFrame[, 2])
colnames(dmatrix) <- letters[1:3]
d2 <- dmatrix[ , 1:2]
f <- lm(testFrame$y ~ d2)
coef(f)[-1]%*%c(2,-1)/3
coef(f)[-1]%*%c(-1,2)/3
coef(f)[-1]%*%c(-1,-1)/3