1
$\begingroup$

I am working on a 10-fold cross validation problem, and am having an issue with part of my code. Specifically, I'm having a problem with my "for (1 in nfold)" argument, and with the variable length of x. Is there a better way to set up cross-validation than this? Also, I'm not familiar with the last error message regarding the variable length of x--what exactly does this mean, and how might I correct it?

I've attached my code (the data set is included in the ElemStatLearn package).

Any help is appreciated, Thanks!

> library(ElemStatLearn)

> library(kknn)

> library(class)

> data(zip.train)

> train=zip.train[which(zip.train[,1] %in% c(2,3)),]

> test=zip.test[which(zip.test[,1] %in% c(2,3)),]

> nfold = 10

> infold = sample(rep(1:10, length.out = (x)))

Warning message:
In rep(1:10, length.out = (x)) :
  first element used of 'length.out' argument

> mydata = data.frame(x = train[,c(-1,-4)] , y = train[,1])

> K = 20

> errorMatrix = matrix(NA, K, 10)
> for (1 in nfold)

Error: unexpected numeric constant in "for (1"
> {
+   for (k in 1:20)
+   {
+     knn.fit = kknn(y ~ x, train = mydata[infold != l, ], test = mydata[infold == l, ], k = k)
+     errorMatrix[k, l] = mean((knn.fit$fitted.values - mydata$y[infold == l])^2)
+   }
+ }

Error in model.frame.default(formula, data = train) : 
  variable lengths differ (found for 'x')
$\endgroup$

closed as off-topic by shadowtalker, user20160, whuber Oct 8 '18 at 22:10

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question appears to be off-topic because EITHER it is not about statistics, machine learning, data analysis, data mining, or data visualization, OR it focuses on programming, debugging, or performing routine operations within a statistical computing platform. If the latter, you could try the support links we maintain." – user20160, whuber
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ You first error message comes form x being a vector with more than one term. What is x? Your second error message comes from trying to use 1 (one) as a variable when you possibly meant l (lower case L). Your third is another problem with x $\endgroup$ – Henry Oct 8 '18 at 22:10
  • $\begingroup$ Henry, Thank you. I must have mistakenly inserted a "1", but replacing that with a lower case "L" seems to have worked. For the remaining issue, I should have clarified exactly what I'm trying to do: zip.train is a matrix with a certain number (0,1,...,9) given in column one, and then various values for pixel coloration/shape/etc... in the remaining columns. There are some 1700+ rows ( so 1700+ individual digits) and a corresponding vector that represents the column values for each entry. That is why I tried to define x as a vector--hopefully that makes more sense. Thanks again! $\endgroup$ – mattyice33x Oct 9 '18 at 0:28