R - Function for 10 fold crossvalidation
I have written a function for 10 fold crossvalidation that I want to use for different models, e.g PPR, MARS. However, I get an error when running it and I cannot figure out why it does not work? My CV function:
cv10 <- function(reg.fn, formula, dataset, ...)
{
set.seed(201)
### Number of observations
nrow <- nrow(dataset)
### Create a permutation of the observations indices
Ind <- sample.int(nrow,nrow, replace = FALSE)
### Compute the size of each of the 10 folds
M <- nrow / 10 # 'fold size'
### Initialize the score
score <- 0
### The first fold will then contain the observations which correspond to..
### ..the indices of the first M elements of Ind.
for(i in 1:10){
beg <- i*M
end <- (i+1)*M
### Data to train the model
data.train <- dataset[Ind[-beg:-end],]
### Data to test the model
data.fold <- dataset[Ind[beg:end],]
### Fit the model
model <- reg.fn(formula,data=data.train,...)
predicted.y <- predict(model,data.fold)
### Update the CV-score
score <- sum((predicted.y - data.fold[,1])^2) / M
}
return(score/10)
}
Testing using ppr:
cv.scores <- numeric(10)
### Some code
for(i in 1:10){
score <- cv10(reg.fn = ppr, formula = y~.,
dataset = data, nterms=i)
cv.scores[i] <- scores
}
cv.scores
The traceback:
Error in matrix(NA, length(keep), object$q, dimnames = list(rn, object$ynames)) : length of 'dimnames' [1] not equal to array extent 4. matrix(NA, length(keep), object$q, dimnames = list(rn, object$ynames)) 3. 613
predict.ppr(model, data.fold) 2. predict(model, data.fold) 1. cv10(reg.fn = ppr, formula = y ~ ., dataset = data, nterms = i)
The data I am using:
structure(list(y = c(23.<PHONE_NUMBER>, 27.8893494373006, 3.32468370559938,
-13.5852336127512, -5.14668013186906, -<PHONE_NUMBER>, -14.328750654513,
-4.26428395686341, -2.75486620989581, 17.3107345018601, 25.6193450849393,
<PHONE_NUMBER>, -1.30909806542865, 2.<PHONE_NUMBER>, -19.1193524499977,
-1.46508279385589, 2.65778970954973, 14.8513018374104, -2.87449028138997,
1.37368992108124, -1.43518738939116, 0.0199676357940499, -1.549025998582,
-4.<PHONE_NUMBER>, -9.15130335901099, -2.62794216480131, -1.68473200963303,
3.15144283445608, 7.78027589015824, 9.<PHONE_NUMBER>), x1 = c<PHONE_NUMBER>,
-<PHONE_NUMBER>, 0.325763726232689, -1.69658096808073, -1.2854825202758,
-0.<PHONE_NUMBER>, <PHONE_NUMBER>, 0.<PHONE_NUMBER>, -2.30403430891787,
0.189004139305415, <PHONE_NUMBER>, <PHONE_NUMBER>, <PHONE_NUMBER>,
1.01347438447768, -<PHONE_NUMBER>, <PHONE_NUMBER>, 0.207342703528518,
0. 856