library (class)

data(iris)

## Split in train + test set
indexes <- sample(1:nrow(iris),as.integer(0.7*nrow(iris)))

trainData <- iris[indexes,]
testData <- iris[-indexes,]

## A 3-nearest neighbors model with no normalization
pred <- knn(train = trainData[, -5], test = testData[, -5], cl = trainData$Species, k=3)

confusionmatrix = as.matrix(table(Actual = testData$Species, Predicted = pred))
accuracy = sum(diag(confusionmatrix))/length(testData$Species)

print('Confusion Matrix')
print(confusionmatrix)
print('Accuracy')
print(accuracy)

DataToPredict <- matrix(c(5.2,3.5,1.4,0.2, 5.7,2.9,3.6,1.3, 5.8,3.0,5.1,1.8), nrow=3, ncol=4)
pred <- knn(train = trainData[, -5], test = DataToPredict[,], cl = trainData$Species, k=3)
print(pred)

