Jerry
Jerry

Reputation: 657

what is the FNN:knn return value?

This is a question about R, not about kNN. Basically, in examining some code, I came across the following incantation:

results <- (0:9)[knn(train, test, labels, k = 10, algorithm="cover_tree")]

I understand what it returns. I just don't understand the (0:n)[<foo>] notation in R. And I've tried other values instead of 0:9, but can't seem to break this in a meaningful way, as well as done due diligence googling.

Can anyone explain this to a Python/Java/C programmer?

Upvotes: 0

Views: 507

Answers (1)

Hao Ye
Hao Ye

Reputation: 205

In R, the code 0:9 returns a vector with values from 0 to 9. The square bracket notation is used for indexing into that vector:

(0:9)[4] # returns the 4th element of the vector 0:9 (or 3)

In this case, because knn returns the classification of the test set as a factor, what this is effectively doing is mapping that classification into the integers from 0 to 9.

(0:9)[1, 3, 1, 5] # returns a vector with 4 values, namely <0, 2, 0, 4>

Upvotes: 1

Related Questions