How can I obtained the estimated variance of a linear model when using R, i.e.

\begin{equation} \widehat{var(y)}. \end{equation}

  • 6
    $\begingroup$ var(fitted(lm_model)) do you need this one? $\endgroup$ – Dmitrij Celov Jun 28 '11 at 12:10
  • $\begingroup$ @Dmitrij Post an answer! $\endgroup$ – user88 Jun 28 '11 at 14:36
  • 2
    $\begingroup$ What does this expression $\widehat{var(y)}$ mean? Suppose the data are $(x_i,y_i)$ and the $y_i$ are random variables with expectations $\beta x_i$ for some unknown coefficient(s) $\beta$. Do you want the variance of the set of $\beta x_i$ (either assuming the $x_i$ are fixed or under some distributional assumptions for them) or do you want to estimate the variance of the $y_i$? The latter is larger than the former. $\endgroup$ – whuber Jun 28 '11 at 19:29

@Dimitrij's comment is right on, and I didn't previously know about the fitted function,

Still, I think that it is helpful to know that the model output includes the fitted values. The content of the model output can be determined using attributes(xymodel), and this will show that xymodel has an item fitted.model that can be accessed using xymodel$fitted.values. Then, it is straightforward to calculate the variance of this vector using the var function:

x <- 1:10  
y <- 2 * (x + runif(10))
xymodel <- lm(y~x)
ans <- var(xymodel$fitted.values)
print(ans) # answer to O.P.

# same as Dimitrij's answer
ans == var(fitted(xymodel))

Not the answer you're looking for? Browse other questions tagged or ask your own question.