I continue to get an error on my function, possibly I'm overlooking something simple. I cannot run the code without getting an error when applying the function.
k.nn <- function(k,p1,p) {                          
k > 0                           
K <-length(k)                               
p=matrix()                                      
for (i in p) {                                             
matrix <- cbind(p,p1[1],p1[2])                  
d <- sqrt((matrix[,1]-matrix[,3])^2+(matrix[,2]-matrix[,4])^2)  
}
##use the sort function to find the smallest distance from 1:k and return all nearest k values
sort.d <- function(x) {                             #implement bubble sort      
N=length(x)                                     
N>0                                                  
c=class(x)                                      
for (n in length(x):2) {                            #distinguish the last term in the vector, name it, much be of x length, consists an error of length 1. Error if you compute n in length(x):1, cover length of 1
if(length(x)<2) 
return(x)
 for (m in 1:(n - 1)) {                             #distinguish the first term in the vector, name it
 if(x[m]>x[m + 1]) {                            #begin comparing each term to neighboring term
swap<-x[m]                                      
x[m]<-x[m + 1]          
x[m + 1]<-swap  
}
}
}
return(x)                                       
}
sorted=sort.d(d)                                    
 for (n in k){
 print(sorted[1:k])}                            
 }
 p=matrix(c(6.9,7.6,7.1,.4,6.2,1.8,2.5,2.3,5.7,6.9,.9,4.4,5.2,1.9,.6,7.4,1.2,6.6,3.3,4.9),nrow=10,ncol=2) #given matrix
p1=c(6,6)                                       
k=3                                         nn.3=k.nn(k,p1,p)                                   
print(nn.3)
 
    