title: random forest: error in dealing with factor levels in R
body: <p>I am using <code>rf</code> model in <code>R</code> to predict a binary outcome 0 or 1. I have categorical variables (coded as numbers) in my input data which are coded as factor while training. I use <code>factor()</code> function in <code>R</code> to convert the variable as factor. So for every categorical variable<code>x</code>,my code is like this.</p>
  
  <pre><code>feature_x1=factor(feature_x1) # Convert the variable into factor in training data. 
  #This variable takes 3 levels 0,1,2
  </code></pre>
  
  <p>This works perfectly fine while training the model. Let us assume my model object is <code>rf_model</code>. While running the model on new data which is just a vector of numbers. I first convert the number into factors for feature_x1</p>
  
  <pre><code>newdata=data.frame(1,2)
  colnames(newdata)=c("feature_x1","feature_x2")
  newdata$feature_x1=factor(newdata$feature_x1)
  score=pred(rf_model,newdata,type="prob")
  </code></pre>
  
  <p>I am receiving the following error </p>
  
  <blockquote>
    <p>Error in predict.randomForest(rf_model, newdata,type = "prob") : 
      New factor levels not present in the training data</p>
  </blockquote>
  
  <p>How to deal with this error, because in reality, after training the model we will always have to deal with data for which outcome is unknown which is a just a single record. </p>
  
  <p>Please let me know if more clarity or code is required</p>