Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In lm.wfit, what does z <- .Call(C_Cdqrls, x *wts, y*wts, tol) do? [duplicate]

Tags:

r

lm

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!

like image 382
user722224 Avatar asked Apr 03 '13 00:04

user722224


1 Answers

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)
like image 116
mnel Avatar answered Sep 16 '22 14:09

mnel