0

I am trying to complete a homework assignment for a class in Analytics. We are using the kknn (K nearest neighbor) function for classification. Anyway, the for loop does not seem to be iterating through the i values as I am intending:

I first tried initializing a list and trying to append it using the double brackets notation, but I noticed, in my Global Environment, that the list just had one item. I tried using the $ notation to append the list, and same result. I then tried starting a data frame and using rbind to extend the frame with each iteration of the for loop , in hopes that it would do the trick. It is still giving me only one item in my dataframe.

klist = list()

for(i in 1:654)
  {CCmodel_knn <- kknn(V11~V1+V2+V3+V4+V5+V6+V7+V8+V9+V10, CCdata[-i,],CCdata[i,],k=10,distance = 2,kernel ="optimal",scale = TRUE)

fittedValues <- fitted.values(CCmodel_knn)

klist$fittedValues <- i}

and I tried klist[[fittedValues]] <- i

Here is the code I used for the dataframe:

kframe <- data.frame(ivalue = i, FV = fittedValues)

for(i in 1:654)
  {CCmodel_knn <- kknn(V11~V1+V2+V3+V4+V5+V6+V7+V8+V9+V10, CCdata[-i,],CCdata[i,],k=10,distance = 2,kernel ="optimal",scale = TRUE)

fittedValues <- fitted.values(CCmodel_knn)

rbind(kframe, i, fittedValues)}

Any suggestions on how to get the for loop to add to my list? As you can see, there my range is i in 1:654, so I am expecting a 654 row dataframe/list.

Tom
  • 2,734
  • 2
  • 22
  • 39
Deemy
  • 1
  • 1
  • Please read [How do I format my code blocks?](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) and edit your question. – jay.sf Jan 15 '20 at 09:22

1 Answers1

0

Your loop is writing to the same variable every time. You need to append it to a list and then process the whole list at the end.

Try this:

klist = list()

for(i in 1:654) 
{
  CCmodel_knn <- kknn(V11 ~ V1 + V2 + V3 + V4 + V5 + V6 + V7 + V8 + V9 + V10, 
                      CCdata[-i,], CCdata[i,], k = 10, distance = 2, 
                      kernel = "optimal", scale = TRUE)

  klist[[i]] <- fitted.values(CCmodel_knn)
}

kframe <- do.call("rbind", klist)

You may then need to do

kframe <- as.data.frame(kframe)
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87