Skip to content
Prev 323361 / 398503 Next

R's basic lm() and summary.lm functions

On Fri, 10 May 2013, ivo welch wrote:

            
If you use NeweyWest() from "sandwich", the code becomes much shorter:

ols2 <- function (..., newey.west= 0, stdcoefs = TRUE)
{
   ## model and summary
   m <- lm(...)
   rval <- summary(m)

   ## Newey-West standard errors and t-statistic
   nw <- sqrt(diag(NeweyWest(m, lag = newey.west, prewhite = FALSE)))
   rval$coefficients <- cbind(rval$coefficients,
     "NW" = nw, "t (NW)" = coef(m)/nw)

   ## standardized coefficients
   if(stdcoefs) rval$coefficients <- cbind(rval$coefficients, "Std. Coef" =
     coef(m) * apply(model.matrix(m), 2, sd) /
     sd(model.response(model.frame(m))))

   return(rval)
}

The ols2(y ~ x + z) produces output equivalent to ols(y ~ x + z).

Personally, I always just use

   m <- lm(....)
   coeftest(m, vcov = NeweyWest)

to get the coefficient tests with Newey-West standard errors. By default, 
this uses automatic lag selection and prewhitening but you can switch both 
off if you want:

   coeftest(m, vcov = NeweyWest(m, lag = 0, prewhite = FALSE))

Best,
Z