0

Let me give some background context: I have a list of 100 vectors, each one with 50 dimensions, and I'd like to associate the first 50 vectors with class A and the last ones with class B.

My question is: How can I do it in order to apply kNN later and which library has a kNN method more appropriate for this?

Thanks in advance.

Karsten W.
  • 17,826
  • 11
  • 69
  • 103
gcolucci
  • 438
  • 1
  • 5
  • 21

1 Answers1

0

One of the first options that come to my mind is to make a data.frame from a list of vectors, create factor indicator and then use knn from class package.

Make a data.frame from a list of vectors

Using rbind, make a matrix and then use as.data.frame function (more examples in this question). Assuming that l is a list of vectors:

data <- as.data.frame(do.call(rbind, l))

Factor indicator

class <- as.factor(c(rep("A", 50), rep("B", 50)))

kNN classification using class package

In case you don't have separate data for testing, probably the best way would be

train.ind <- sample(1:100, 75) # making indexes to split data into 75% train and 25% test
resulting.classes <- knn(train = data[train.ind, ], test = data[-train.ind, ], cl = class)

And if you have separate train and test data then just use

resulting.classes <- knn(train = train.data, test = test.data, cl = class)

Other choices for kNN that might be useful - ‘kknn’ package and 'FNN' package., but class package seems the easiest one for simple kNN classification.

Community
  • 1
  • 1
romants
  • 3,660
  • 1
  • 21
  • 33