I have a question about sapply
in R. In my example I'm using it for leave-one-out cross validation
##' Calculates the LOO CV score for given data and regression prediction function
##'
##' @param reg.data: regression data; data.frame with columns 'x', 'y'
##' @param reg.fcn: regr.prediction function; arguments:
##' reg.x: regression x-values
##' reg.y: regression y-values
##' x: x-value(s) of evaluation point(s)
##' value: prediction at point(s) x
##' @return LOOCV score
loocv <- function(reg.data, reg.fcn)
{
## Help function to calculate leave-one-out regression values
loo.reg.value <- function(i, reg.data, reg.fcn)
return(reg.fcn(reg.data$x[-i],reg.data$y[-i], reg.data$x[i]))
## Calculate LOO regression values using the help function above
n <- nrow(reg.data)
loo.values <- sapply(seq(1,n), loo.reg.value, reg.data, reg.fcn)
## Calculate and return MSE
return(???)
}
My questions about sapply
are the following:
- Can I use multiple arguments and functions, i.e.
sapply(X1,FUN1,X2,FUN2,..)
, whereX1
andX2
are my function arguments for the functionFUN1
andFUN2
respectively. - In the above code, I apply
1:n
to the functionloo.reg.value
. However, this function has multiple arguments, in fact 3: integeri
, regression datareg.data
and regression functionreg.fcn
. If the function in sapply has more than one argument, and myX
covers just one of the arguments, does sapply use it as "first argument"? So it would be the same assapply(c(1:n,reg.data,reg.fcn),loo.reg.value, reg.data, reg.fcn)
?
Thank you for your help