3

How can I call residuals out from function cv.lm?

cv.lm$ss gives me the cross validation sum of squares, but I need individual residuals from each fold.

Is it possible to call out?

Jeromy Anglim
  • 42,044
  • 23
  • 146
  • 250
user4917
  • 33
  • 3

1 Answers1

3

Looking at the R code, computation for individual fold are done in the inner loop, starting with

for (i in sort(unique(rand))) { # line 37

but results are just returned with a print statement (line 67-68), if printit=TRUE (which is the default). So, you can use what I suggested for a related question and edit the function in place so that it returns the SS for each fold in a list. That is, use

fix(cv.lm)

at the R prompt, then add the following three lines in the code

...
sumss <- 0
sumdf <- 0
ssl <- list()            # (*)
...
    ms <- ss/num
    ssl[[i]] <- ss       # (*)
    if (printit)
        cat("\nSum of squares =", round(ss, 2), "   Mean square =",
...
invisible(c(ss = sumss, df = sumdf, 
          ss.fold=ssl))  # (*)
}

To check that it worked, try

> res <- cv.lm(printit=FALSE, plotit=FALSE)
> str(res)
List of 5
  ss      : num 59008
  df      : num 15
  ss.fold1: num 24351
  ss.fold2: num 20416
  ss.fold3: num 14241

You can also returned a list of the fold SS by replacing ss.fold=ssl with ss.fold=list(ssl), so that the output would look like

List of 3
  ss     : num 59008
  df     : num 15
  ss.fold:List of 3
  ..$ : num 24351
  ..$ : num 20416
  ..$ : num 14241
chl
  • 50,972
  • 18
  • 205
  • 364
  • I'm in doubt about same point. But i think that this package was updated and i didnt find where should i add this 3 lines. Could you help me? –  Aug 05 '13 at 14:09
  • @Arthur Indeed, it has been updated! (The contrary would have been surprising.) Not a big deal, though: you can follow the above steps by noting that the inner loop now starts around line 97 (depending on your version of `DAAG`; mine is 1.15, packaged on 2012-07-26 10:02:12 UTC). – chl Aug 05 '13 at 16:49