title: How can I resolve the following dimension mismatch with R's K nearest neighbors?
body: <p>In the code below, I am trying to use K nearest neighbors with a single predictor. 
  To the best of my understanding, there's no need for the number of examples in <code>train.X</code> to match the number of examples in <code>test.X</code>, but <code>R</code> seems to not be parsing my input correctly.</p>
  
  <pre><code>library(ISLR)
  library(class)
  
  train=(Weekly$Year&lt;2009)
  train.X = Weekly$Lag2[train]
  test.X = Weekly$Lag2[!train]
  train.Direction = Weekly$Direction[train]
  knn.pred = knn(train.X, test.X, train.Direction, k=1)
  </code></pre>
  
  <p>When the code above is run, it gets the error</p>
  
  <pre><code>   Error in knn(train.X, test.X, train.Direction, k = 1) :   
        dims of 'test' and 'train' differ                       
  </code></pre>
  
  <p>How can I fix <code>train.X</code> and <code>test.X</code> so that <code>R</code> parses them correctly?</p>