rasch.lda.cv <- function (Xtrain, Ytrain, ncomp, nruncv = 20, alpha = 2/3, priors = NULL) 
{
    if (length(ncomp) == 1) {
        if (ncomp == 1) 
            return(ncomp)
        else ncomp <- 1:ncomp
    }
    n <- nrow(Xtrain)
    #ntrain <- floor(n * alpha)
    ntrain <- n-1
    samp <- matrix(0, ntrain, nruncv)
    for (i in 1:nruncv) {
        samp[, i] <- sample(n, ntrain)
    }
    samp <- as.data.frame(samp)
    errorcv <- sapply(samp, FUN = rasch.lda.sample, Xtrain, Ytrain, 
        ncomp = ncomp, priors = priors)
    meanerror <- apply(errorcv, MARGIN = 1, FUN = mean)
    ncomp <- ncomp[which.min(meanerror)]
    return(list(samp = samp, errorcv = errorcv, ncomp = ncomp))
}



