2

So I am getting an error on line: (testDistance < distance) {

Error: missing value where TRUE/FALSE needed Any idea why this is happening? From what I've googled this error is somehow associated with either testDistance or distance not existing at some point? I dont understand because they should both be initialized before the code is run.

one.nn <- function(training.data,sample){
  #training.data is expected to be a dataframe

  #distance function
  dist <- function(x1,x2) {
      sum = 0
      for (i in 1:length(x1)) {
         num = (x1[i] - x2[i])^2
         sum = sum + num
      }    
     distance = sqrt(sum)
     return(distance)
 }

  #get the dataframe and seperate the data from the classes (omit first row of each)
  labels <- as.matrix(training.data[-1,ncol(training.data)])
  features <- as.matrix(training.data[-1,1:(ncol(training.data)-1)])


  #initial neighbor is the first one
  nearestNeighbor = features[1,]
  distance = dist(strtoi(features[1,]),sample)

  #loop through data to find nearest neighbor by calculating distance and storing its class
  for (i in 1:nrow(features)){
    testDistance = dist(strtoi(features[i,]),sample)
    if (testDistance < distance){
      distance = testDistance
      nearestNeighbor = features[i,]
      #We found the current nearest neighbor, lets save the class of it for later
      class = labels[i,]
    }
  }

  #return class of the sample to be classified
   return (class)
}
asdf
  • 657
  • 1
  • 13
  • 30

0 Answers0