title: "Factor has new levels" error for variable I'm not using
body: <p>Consider a simple dataset, split into a training and testing set:</p>
  
  <pre><code>dat &lt;- data.frame(x=1:5, y=c("a", "b", "c", "d", "e"), z=c(0, 0, 1, 0, 1))
  train &lt;- dat[1:4,]
  train
  #   x y z
  # 1 1 a 0
  # 2 2 b 0
  # 3 3 c 1
  # 4 4 d 0
  test &lt;- dat[5,]
  test
  #   x y z
  # 5 5 e 1
  </code></pre>
  
  <p>When I train a logistic regression model to predict <code>z</code> using <code>x</code> and obtain test-set predictions, all is well:</p>
  
  <pre><code>mod &lt;- glm(z~x, data=train, family="binomial")
  predict(mod, newdata=test, type="response")
  #         5 
  # 0.5546394 
  </code></pre>
  
  <p>However, this fails on an equivalent-looking logistic regression model with a "Factor has new levels" error:</p>
  
  <pre><code>mod2 &lt;- glm(z~.-y, data=train, family="binomial")
  predict(mod2, newdata=test, type="response")
  # Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
  #   factor y has new level e
  </code></pre>
  
  <p>Since I removed <code>y</code> from my model equation, I'm surprised to see this error message. In my application, <code>dat</code> is very wide, so <code>z~.-y</code> is the most convenient model specification. The simplest workaround I can think of is removing the <code>y</code> variable from my data frame and then training the model with the <code>z~.</code> syntax, but I was hoping for a way to use the original dataset without the need to remove columns.</p>