Acarbalacar
Acarbalacar

Reputation: 734

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

Upvotes: 0

Views: 13329

Answers (3)

Dason
Dason

Reputation: 61953

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

Upvotes: 1

p11k
p11k

Reputation: 11

In your R code, w is a vector. It should be a diagonal matrix:

Replace this line:

w <- as.vector(c(7,8,9))

by this:

w <- as.vector(c(7,8,9))*diag(3)

Upvotes: 1

SabDeM
SabDeM

Reputation: 7190

I am a little rusty on regressions but I think the hatvalues function is what you are looking for. ?hatvalues provides a useful of other diagnostics.

Upvotes: 1

Related Questions