simple 1NN

I'm confused here as i'm unable to figure out why code is not working as expected on entire test data set. Same code works when I use it to predict value of 1 test data. 
Sorry, I'm having a hard time parsing this code in my brain... you've got an anonymous function inside of an apply called by an anonymous function inside an apply, and that's too many layers for me to easily parse! To debug this, I would focus on checking that you are passing the data (and data types) that you intended to pass to each level. Or, change at least one apply to a for loop and perhaps it will become clearer.