R - Error in KNN - Test and training differ I am trying to classify set of text files whether it belong to category A or category B using KNN algorithm

Here is the error that i get

&gt; knn.pred &lt;- knn(tdm.stack.nl, tdm.stack.nl_test, tdm.cand)  



  Error in knn(tdm.stack.nl, tdm.stack.nl_test, tdm.cand) :      dims of
  'test' and 'train' differ


 &gt; dim(tdm.stack.nl)  
    [1]  184 1599  
    &gt; dim(tdm.stack.nl_test)  
    [1]   1 992  


As obvious the number of words used by training dataset is different from train. How can I avoid this?

I want to mention that this error i get when i divide the training and test dataset manually to (70:30) ratio. However i dont get this error if i divide the training and test dataset using samlpling method.

&gt; # create hold-out   
&gt; set.seed(500)  
&gt; train.idx &lt;- sample(nrow(tdm.stack), ceiling(nrow(tdm.stack) * 0.7))   
&gt; test.idx &lt;- (1:nrow(tdm.stack))[-train.idx]   
&gt; 
&gt; # create model - knn clustering
&gt; tdm.cand &lt;- tdm.stack[, "targetcandidate"]
&gt; tdm.stack.nl &lt;- tdm.stack[, !colnames(tdm.stack) %in% "targetcandidate"]
&gt; 
&gt; # set up model
&gt; knn.pred &lt;- knn(tdm.stack.nl[train.idx,], tdm.stack.nl[test.idx,],    tdm.cand[train.idx])  
&gt; dim(tdm.stack.nl[train.idx,])  
[1]  129 1599  
&gt; dim(tdm.stack.nl[test.idx,])  
[1]   55 1599   


However this method will not work for me as I want to classify a document in a real time using the model that was built before.

Please help. Kindly let me know if you need any other info. 
Arun
You are avoiding the error with sampling purely by chance (the words are common). Simplest way would be to merge training and test, construct a tdm on a joined set, separate into training and test again and then purge some columns (the constant ones in the train set, as they correspond to words occurring in test only => useless for training).