title: R SVM Predict - Error in predict.svm: test data does not match model
body: <p>I started with a data frame of 23,515 rows and 3 columns. I split the data 70/30 into training/testing. I am fitting a classification model with SVM from the e1071 package to predict variable MISSING. After I fit the model, I attempt to predict MISSING in my test set but I get the error below:</p>
  
  <pre><code>&gt; ftplh_svm &lt;- svm(MISSING ~ V1+V2, data=train_vars, type="C-classification", kernel="linear")
  &gt; p &lt;- predict(ftplh_svm, test_vars, type="class")
  Error in predict.svm(object, ...) : test data does not match model !
  </code></pre>
  
  <p>I tried removing the predicted class from the test set as recommended in another post:</p>
  
  <pre><code>&gt; p &lt;- predict(ftplh_svm, test_vars[-3], type="class")
  Error in predict.svm(object, ...) : test data does not match model !
  </code></pre>
  
  <p>I also tried dropping empty levels as recommended by <a href="https://stackoverflow.com/users/7623055/brad">Brad</a>, but no levels ended up being dropped and I got the same results:</p>
  
  <pre><code>&gt; train_vars$V1 &lt;- droplevels(as.factor(train_vars$V1))
  &gt; train_vars$V2 &lt;- droplevels(as.factor(train_vars$V2))
  &gt; train_vars$MISSING &lt;- droplevels(as.factor(train_vars$MISSING))
  &gt; test_vars$V1 &lt;- droplevels(as.factor(test_vars$V1))
  &gt; test_vars$V2 &lt;- droplevels(as.factor(test_vars$V2))
  &gt; test_vars$MISSING &lt;- droplevels(as.factor(test_vars$MISSING))
  &gt; ftplh_svm &lt;- svm(MISSING ~ V1+V2, data=train_vars, type="C-classification", kernel="linear")
  &gt; p &lt;- predict(ftplh_svm, test_vars, type="class")
  Error in predict.svm(object, ...) : test data does not match model !
  </code></pre>
  
  <p>Structure of my training set and test set:</p>
  
  <pre><code>&gt; str(train_vars)
  'data.frame':   16395 obs. of  3 variables:
   $ V1: Factor w/ 148 levels "AAC","AAL","AGP",..: 1 1 2 2 2 2 2 2 2 2 ...
   $ V2  : Factor w/ 284 levels "6AR","AAC","AAL",..: 79 42 180 180 180 180 180 180 180 180 ...
   $ MISSING      : Factor w/ 2 levels "FALSE","TRUE": 1 1 1 1 1 1 1 1 1 1 ...
  &gt; str(test_vars)
  'data.frame':   7129 obs. of  3 variables:
   $ V1: Factor w/ 111 levels "AAC","AAL","AGP",..: 1 2 2 2 2 2 2 2 2 2 ...
   $ V2  : Factor w/ 265 levels "AAC","AAL","ABZ",..: 225 169 169 169 169 169 169 169 169 169 ...
   $ MISSING      : Factor w/ 2 levels "FALSE","TRUE": 1 1 1 1 1 1 1 1 1 1 ...
  </code></pre>
  
  <p>Test to see if there are new levels in my test set (I did this for each variable):</p>
  
  <pre><code>&gt; train_lev &lt;- levels(train_vars$V1)
  &gt; test_lev &lt;- levels(test_vars$V1)
  &gt; # these levels only exist in the test set
  &gt; new_levels &lt;- setdiff(test_lev,train_lev)
  &gt; new_levels
  character(0)
  &gt; # how many observations is it?
  &gt; obs &lt;- which(test_vars$V1 %in% new_levels)
  &gt; length(obs)
  [1] 0
  </code></pre>