Search code examples
rnlm

Source code of nlm function in stats package


I need to find the source code of the nlm function.

When I use

edit(nlm)

below code appears

function (f, p, ..., hessian = FALSE, typsize = rep(1, length(p)), 
    fscale = 1, print.level = 0, ndigit = 12, gradtol = 1e-06, 
    stepmax = max(1000 * sqrt(sum((p/typsize)^2)), 1000), steptol = 1e-06, 
    iterlim = 100, check.analyticals = TRUE) 
{
    print.level <- as.integer(print.level)
    if (print.level < 0 || print.level > 2) 
        stop("'print.level' must be in {0,1,2}")
    msg <- (1 + c(8, 0, 16))[1 + print.level]
    if (!check.analyticals) 
        msg <- msg + (2 + 4)
    .External2(C_nlm, function(x) f(x, ...), p, hessian, typsize, 
        fscale, msg, ndigit, gradtol, stepmax, steptol, iterlim)
}

now when I want to see what is insode C_nlm

I tried

stats:::C_nlm

and I get

$name
[1] "nlm"

$address
<pointer: 0x0000000004a83920>
attr(,"class")
[1] "RegisteredNativeSymbol"

$dll
DLL name: stats
Filename: C:/Program Files/R/R-3.1.2/library/stats/libs/x64/stats.dll
Dynamic lookup: FALSE

$numParameters
[1] 11

attr(,"class")
[1] "ExternalRoutine"  "NativeSymbolInfo"

After some web search I found out that I need to use grep after this.

But I am not getting how to use it. I tried these references

How to locate code called by .External2()?

How can I view the source code for a function?

Can anyone please tell me how to proceed further?


Solution

  • You can browse the R source code at this GitHub repo: r-source.

    Search it for the term "SEXP nlm" since stats:::C_nlm points to a function with the name "nlm" and all functions returning data to R use a datatype called SEXP (S expression).

    You'll get two hits in the files statsR.h and optimize.c. The c-file is what you are looking for, so go down to the line starting with SEXP nlm and you got it.

    SEXP nlm(SEXP call, SEXP op, SEXP args, SEXP rho)
    {
        SEXP value, names, v, R_gradientSymbol, R_hessianSymbol;
    
        double *x, *typsiz, fscale, gradtl, stepmx,
        steptol, *xpls, *gpls, fpls, *a, *wrk, dlt;
    
        int code, i, j, k, itnlim, method, iexp, omsg, msg,
        n, ndigit, iagflg, iahflg, want_hessian, itncnt;
    
    
    /* .Internal(
     *  nlm(function(x) f(x, ...), p, hessian, typsize, fscale,
     *      msg, ndigit, gradtol, stepmax, steptol, iterlim)
     */
        function_info *state;