# 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

> knn.pred <- 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

 > dim(tdm.stack.nl)
[1]  184 1599
> 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.

> # create hold-out
> set.seed(500)
> train.idx <- sample(nrow(tdm.stack), ceiling(nrow(tdm.stack) * 0.7))
> test.idx <- (1:nrow(tdm.stack))[-train.idx]
>
> # create model - knn clustering
> tdm.cand <- tdm.stack[, "targetcandidate"]
> tdm.stack.nl <- tdm.stack[, !colnames(tdm.stack) %in% "targetcandidate"]
>
> # set up model
> knn.pred <- knn(tdm.stack.nl[train.idx,], tdm.stack.nl[test.idx,],    tdm.cand[train.idx])
> dim(tdm.stack.nl[train.idx,])
[1]  129 1599
> 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.