Search code examples
rmatrixlinear-regression

Non-conformability error in multiplication of a matrix by a scalar


I cannot see why I am getting a non-conformability error in the following:

data(mtcars)
x <- as.matrix(subset(mtcars, select = -c(disp)))
x <- cbind(x,rep(1, times = nrow(x)))
y <- as.matrix(mtcars$disp)
beta <- solve(t(x) %*% x) %*% t(x) %*% y
ehat <- y - x %*% beta
Var_OLS = ((1/(nrow(x) - ncol(x))) * (t(ehat) %*% ehat)) * (solve(t(x) %*% x))

The term ((1/(nrow(x) - ncol(x))) * (t(ehat) %*% ehat)) is a scalar. And (solve(t(x) %*% x)) works fine on its own. What is going on here?


Solution

  • ((1/(nrow(x) - ncol(x))) * (t(ehat) %*% ehat)) is a matrix, so is (solve(t(x) %*% x)). Here the rules of matrix multiplication are applied. Since it doesn't satisfy them you get non-conformable arrays error.

    Change ((1/(nrow(x) - ncol(x))) * (t(ehat) %*% ehat)) to a vector since it has only 1 value and it should work.

    Var_OLS = ((1/(nrow(x) - ncol(x))) * (t(ehat) %*% ehat))[, 1] * (solve(t(x) %*% x))