How to calculate $\sum(X_i-\bar{X})^2$ in R

3.6k Views Asked by At

I'm trying to figure out how to calculate $\sum(X_i-\bar{X})^2$ in R, specifically identifying it in either the aov function or $\operatorname{lm}(y\sim x)$ function. I am trying to use it to calculate the s $\{\hat{Y}\}$ value in a regression confidence interval.

1

There are 1 best solutions below

0
On BEST ANSWER

If you use the command $\operatorname{anova}(\operatorname{lm}(x\sim1))$ then the sum of squares due to error should be exactly $\sum_{i=1}^n (x_i - \bar x)^2$.

Alternatively sum((x-mean(x))^2) should do it.

I tried it with an example:

anova(lm(x~1))
Analysis of Variance Table

Response: x
Df Sum Sq Mean Sq F value Pr(>F)
Residuals 24 34.516 1.4382

sum((x-mean(x))^2)
[1] 34.51644

The first command gives you $34.516$ and the second gives you $34.51644$.