Search code examples
rlmleast-squares

Calculating 'hat' matrix in R


In calculating the 'hat' matrix in weighted least squares a part of the calculation is

X^T*W*X

However, I am unsure how one would do this in R

See the following example:

x <- matrix(c(1,2,3,4,5,6),nrow=3,ncol=2,byrow=T)
xt <- t(x)
w <- as.vector(c(7,8,9))

xt*w%*%x

Which gives the error:

Error in xt * w %*% x : non-conformable arrays

Is there anything basic I have misunderstood?

EDIT

xt%*%w%*%x

gives the error:

Error in xt %*% w %*% x : non-conformable arguments

Solution

  • w needs to be 3x3 so make use diag to construct w as a matrix with those values on the diagonal instead of using a vector

    x <- matrix(c(1,2,3,4,5,6),nrow=3,ncol=2,byrow=T)
    xt <- t(x)
    w <- diag(c(7,8,9))
    
    xt %*% w %*% x