title: How to keep all levels of categorical variables when splitting data frame in test and train set in R
body: <p>Sometimes when splitting a data frame with categorical columns into a test and train set, the train set will not contain all levels of the categorical variable. When you then train the model, and try to predict the test set, the prediction will fail with:</p>
  
  <p>For example:</p>
  
  <pre><code>x &lt;- data.frame(...) # data frame with columns with very dispersed categorical variables
  set.seed(123)
  smp_size &lt;- floor(0.75 * nrow(x))
  train_idx &lt;- sample(seq_len(nrow(x)), size = smp_size)
  train_set &lt;- x[train_idx, ]
  test_set &lt;- x[-train_idx, ]
  m &lt;- lm(some_formula, data=train_set)
  predict(m, newdata=test_set)
  
  Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :  
      factor xxxx has new levels yyy ...
  </code></pre>
  
  <p>Does anyone know a handy way to set the levels of all categorical variables in both train and test set to the levels in the original data set ?</p>
  
  <p>Thank you.</p>