所以我在线上收到错误:(testDistance< distance){
错误:缺少需要TRUE / FALSE的值 知道为什么会这样吗?从我用Google搜索的内容来看,这个错误在某种程度上与testDistance或某个点上不存在的距离有关?我不明白,因为它们都应该在代码运行之前进行初始化。
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)
}