0

this may seem like a novice question, but I'm struggling to understand why this doesn't work.

answer = c()
for(i in 1:8){
  answer = c()
  knn.pred <- knn(data.frame(train_week$Lag2), data.frame(test_week$Lag2), train_week$Direction, k=i)
  test <- mean(knn.pred == test_week$Direction)
  append(answer, test)
}

I want the results 1-8 in a vector called answer. it should loop through 8 times, so ideally a vector with 8 numbers would be my output. When I run the for loop, I only get the final answer, meaning it isn't appending. any help would be appreciated, sorry for the novice question, really trying to learn R.

WycG
  • 141
  • 1
  • 1
  • 5

2 Answers2

2

First of all, please include a reproducible example in your question next time. See How to make a great R reproducible example?.

Second, you set answer to c() in the first line of your loop, so this happens in each iteration.

Third, append, just like almost all functions in R, does not modify its argument in place, but it returns a new object. So the correct code is:

answer = c()
for (i in 1:8){
  knn.pred <- knn(data.frame(train_week$Lag2), data.frame(test_week$Lag2), 
                  train_week$Direction, k = i)
  test <- mean(knn.pred == test_week$Direction)
  answer <- append(answer, test)

}

While this wasn't the question, I can't help noting that this is a very inefficient way of creating vectors and lists. It is an anti-pattern. If you know the length of the result vector, then allocate it, and set its elements. E.g

answer = numeric(8)
for (i in 1:8){
  knn.pred <- knn(data.frame(train_week$Lag2), data.frame(test_week$Lag2), 
                  train_week$Direction, k = i)
  test <- mean(knn.pred == test_week$Direction)
  answer[i] <- test

}

Community
  • 1
  • 1
Gabor Csardi
  • 10,705
  • 1
  • 36
  • 53
1

You are overwriting answer inside the for loop. Try removing that line. Also, append doesn't act on its arguments directly; it returns the modified vector. So you need to assign it.

answer <- c()
for(i in 1:8){
  knn.pred <- knn(data.frame(train_week$Lag2), data.frame(test_week$Lag2), train_week$Direction, k=i)
  test <- mean(knn.pred == test_week$Direction)
  answer <- append(answer, test)
}
farnsy
  • 2,282
  • 19
  • 22