[datatable-help] computation of variance covariance matrix for weighted least squares
Dirkules
niklasdornbusch at web.de
Thu Mar 1 12:05:24 CET 2018
Hi,
I am trying to compute the variance covariance matrix in weighted least
squares. Using the lm function gives me a different result as when I am
computing it myself. Any idea what I am doing incorrectly? My calculation
for the beta coefficients seem correct though. Here is my code
library('foreign')
download.file('http://fmwww.bc.edu/ec-p/data/wooldridge/smoke.dta','smoke.dta',mode='wb')
smoke<-read.dta('smoke.dta')
######################################################################################
#computation of my weighting matrix "hhat"
lm.8.7<-lm(cigs ~ lincome + lcigpric + educ + age + agesq + restaurn,
data=smoke)
lres.u<-log(lm.8.7$residuals^2)
lm.8.7gls.u<-lm(lres.u ~ lincome + lcigpric + educ + age + agesq + restaurn,
data=smoke)
hhat<-exp(lm.8.7gls.u$fitted.values)
# estimating with weights hhat
lm.8.7gls<-lm(cigs ~ lincome + lcigpric + educ + age + agesq + restaurn,
weights=1/hhat, data=smoke)
########################################################################################
# Doing the estimation myself
u <- model.frame(cigs ~ lincome + lcigpric + educ + age + agesq +
restaurn, data=smoke)
x <- model.matrix(u, smoke)
y <- model.response(u)
wg <- 1/hhat
hh <- diag(wg)
beta <- solve(t(x) %*% hh %*% x) %*% (t(x) %*% hh %*% y) # estimate of
beta
dSigmaSq <- sum((y - x%*%beta)^2)/(nrow(x)-ncol(x)) # estimate of
sigma-squared
vcm <- dSigmaSq * solve(t(x) %*% hh %*% x) ## compute variance covariance
matrix
t(beta)
lm.8.7gls$coefficients
vcm
vcov(lm.8.7gls)
Many thanks!
--
Sent from: http://r.789695.n4.nabble.com/datatable-help-f2315188.html
More information about the datatable-help
mailing list