My overarching question is, how does R calculate R^2 in the WLS case? It doesn't just weight the observations and then calculate the R^2. To try and figure this out, I was going through the source code until I ran into this in the lm.wfit
code:
z <- .Call(C_Cdqrls, x *wts, y*wts, tol)
What is being done here? Does anyone know how I can access the code for this to get to the details? I.e., what is being returned to z
? How are C_Cdqrls
, x*wts
, y*wts
, tol
being used?
What I understand so far (and I'm not sure if it's right), is that .Call
means that R is executing this code in C. However, I'd like to see how this is done in C if possible.
Thanks!
The R squared
value is actually calculated when calling summary.lm
, you can look at the source code for any function, either in the actual svn repository (https://svn.r-project.org/R/), or this read only mirror on github.
Looking in https://github.com/wch/r-source/blob/trunk/src/library/stats/R/lm.R for
summary.lm
we see the following accounting for the weights (w
)
r <- z$residuals
f <- z$fitted.values
w <- z$weights
if (is.null(w)) {
mss <- if (attr(z$terms, "intercept"))
sum((f - mean(f))^2) else sum(f^2)
rss <- sum(r^2)
} else {
mss <- if (attr(z$terms, "intercept")) {
m <- sum(w * f /sum(w))
sum(w * (f - m)^2)
} else sum(w * f^2)
rss <- sum(w * r^2)
r <- sqrt(w) * r
}
# ..... some other code
# ... then this definition
ans$r.squared <- mss/(mss + rss)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With