title: Error in predict.randomForest
body: <p>I was hoping someone would be able to help me out with an issue I am having with the prediction function of the randomForest package in R. I keep getting the same error when I try to predict my test data:</p>
  
  <p>Here's my code so far:</p>
  
  <pre><code>extractFeatures &lt;- function(RCdata) {
   features                     &lt;- c(4, 9:13, 17:20)
   fea                          &lt;- RCdata[, features]
   fea$Week                     &lt;- as.factor(fea$Week)
   fea$Age_Range                &lt;- as.factor(fea$Age_Range)
   fea$Race                     &lt;- as.factor(fea$Race)
   fea$Referral_Source          &lt;- as.factor(fea$Referral_Source)
   fea$Referral_Source_Category &lt;- as.factor(fea$Referral_Source_Category)
   fea$Rehire                   &lt;- as.factor(fea$Rehire)
   fea$CLFPR_.HS                &lt;- as.factor(fea$CLFPR_.HS)
   fea$CLFPR_HS                 &lt;- as.factor(fea$CLFPR_HS)
   fea$Job_Openings             &lt;- as.factor(fea$Job_Openings)
   fea$Turnover                 &lt;- as.factor(fea$Turnover)
   return(fea)
   }
  
  gp       &lt;- runif(nrow(RCdata))
  RCdata   &lt;- RCdata[order(gp), ]
  train    &lt;- RCdata[1:4600, ]
  test     &lt;- RCdata[4601:6149, ]
  
  rf &lt;- randomForest(extractFeatures(train), suppressWarnings(as.factor(train$disposition_category)), ntree=100, importance=TRUE)
      testpredict &lt;- predict(rf, extractFeatures(test))
      "Error in predict.randomForest(rf, extractFeatures(test)) : 
            Type of predictors in new data do not match that of the training data."
  </code></pre>
  
  <p>I have tried adding in the following line to the code, and still receive the same error:</p>
  
  <pre><code>testpredict &lt;- predict(rf, extractFeatures(test), type="prob")
  </code></pre>
  
  <p>I found the source of the error being the fact that the training data has a level or two that is not found in the test data. So when I tried another suggestion I found online to adjust the levels of the test data to that of the training data, I keep getting NULL values in the fields I am using in both the training and test sets.</p>
  
  <pre><code>levels(test$Referral)
  NULL
  </code></pre>
  
  <p>I can see the levels when I use the function, however. </p>
  
  <pre><code>levels(as.factor(test$Referral))
  </code></pre>
  
  <p>So then I tried the same suggestion I found online with adjusting the levels of the test to equal that of the training data using the following function and received an error:</p>
  
  <pre><code>levels(as.factor(test$Referral)) -&gt; levels(as.factor(train$Referral))
  Error in `levels&lt;-.factor`(`*tmp*`, value = c(...  : 
    number of levels differs
  </code></pre>
  
  <p>I am sure there is something simple I am missing (I am still very new to R), so any insight you can provide would be unbelievably helpful. Thanks!</p>