Search code examples
ropen-sourcemgcv

Seeking well-commented versions of mgcv source code


Apologies for cross-posting (on R-help) but SO gets more views, and I hope someone who knows might find the question here.

I'm looking for well-commented versions of various functions comprising mgcv, so that I can modify a piece of it for a project I'm working on. In particular I'm looking for

  • testStat
  • summary.gam
  • liu2
  • simf

I know that I can find these by typing mgcv:::whatever. But there are a lot of nested if statements, making it difficult to follow. Comments in the code describing exactly what is happening at each step would make my life a lot easier.

Where can I find more-detailed versions of the code? Do such things exist?

EDIT: In response to the deleted comment: I didn't know that it could be found on github, not having used it before. FFR, it's here: https://github.com/cran/mgcv


Solution

  • Have you searched GitHub for any of the source code? There is commented code there. I found testStat in the mgcv.r file.


    Here are a couple of suggestions that help me understand complex code:

    (1) Write the source to a text file so you can space it out, move things around, etc.

    > sink("testStat.txt")
    > mgcv:::testStat
    > sink()
    

    (2) Break its body into a list of its parts

    > x <- as.list(body(mgcv:::testStat))
    > x
    [[1]]
    `{`
    
    [[2]]
    qrx <- qr(X, tol = 0)
    
     ...
    
    [[19]]
    if (nu > 0) {
        if (k1 == 1) 
            rank1 <- val <- 1
        else {
            val <- rep(1, k1)
            rp <- nu + 1
            val[k] <- (rp + sqrt(rp * (2 - rp)))/2
            val[k1] <- (rp - val[k])
        }
        if (res.df <= 0) 
            pval <- liu2(d, val)
        else pval <- simf(d, val, res.df)
    } else {
        pval <- 2
    }
    
     ...
    
    [[21]]
    list(stat = d, pval = min(1, pval), rank = rank)