如何查看R语言lm.fit函数中.Call调用的C_Cdqrls代码?
.Call(C_Cdqrls, x, y, tol, FALSE) in R's lm.fit Great question—digging into this is a fantastic way to understand the nuts and bolts of how R computes regression coefficients, since so many core stats functions rely on optimized compiled code under the hood. Here's a clear, step-by-step breakdown to get to the source:
1. Pinpoint the Package and Registered C Function
First, lm.fit belongs to R's built-in stats package, so we’ll focus on that package’s source code. The C_Cdqrls name in your .Call call is a registered alias—R uses these to link R-level calls to compiled C/Fortran functions.
To confirm the mapping, look at the stats package’s dynamic registration file (usually src/Rdynload.c in the source code). You’ll find an entry like this:
static const R_CallMethodDef CallEntries[] = { // ... other registered functions ... {"C_Cdqrls", (DL_FUNC) &cdqrls, 4}, // ... };
This tells us C_Cdqrls maps to a C function named cdqrls that accepts 4 arguments (matching the x, y, tol, FALSE in your original call).
2. Locate the C Wrapper Function
Next, find the implementation of cdqrls in the stats package’s src directory—look for the file dqrls.c. This is a lightweight C wrapper that converts R’s native objects (SEXPs) into types compatible with Fortran, then calls the underlying numerical routine.
The core of this wrapper looks something like:
SEXP cdqrls(SEXP x, SEXP y, SEXP tol, SEXP has_intercept) { // Convert R inputs to Fortran-compatible variables int n = INTEGER(GET_DIM(x))[0], p = INTEGER(GET_DIM(x))[1]; double *xp = REAL(x), *yp = REAL(y); double tol_val = asReal(tol); // ... additional variable setup ... // Call the Fortran QR-based least squares routine F77_CALL(dqrls)(&n, &p, xp, &n, yp, &ny, &tol_val, coef, resid, effects, &rank, pivot, work, &lwork, info); // Convert Fortran outputs back to R objects and return // ... }
3. Access the Fortran Core Logic
The actual regression coefficient calculation happens in the Fortran routine dqrls, which lives in src/dqrls.f in the stats package source. This file contains the optimized QR decomposition algorithm with column pivoting—the standard, numerically stable method for solving ordinary least squares problems.
How to Get the Source Code
To access these files directly:
- Use R to download the source package for stats:
download.packages("stats", destdir = "./stats_source", type = "source") - Unzip the downloaded
.tar.gzfile, then navigate to thesrcfolder to finddqrls.canddqrls.f.
内容的提问来源于stack exchange,提问作者Thomas Vlasak

