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?
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?
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