title: R error when modifying model variables: "model frame and formula mismatch in model.matrix()"
body: <p>I wanted to write a function which takes a model, calculates the vif, and returns a new model with the collinear variables removed. Here's my code:</p>
  
  <pre><code>remodel_vif &lt;- function(mdl, vif_cutoff){
  
  bad_x &lt;- mdl %&gt;% car::vif() %&gt;% {which(. &gt; vif_cutoff)}
  new_df &lt;- mdl$model %&gt;% dplyr::select(.,-bad_x) 
  return(lm(new_df))
  
  }
  </code></pre>
  
  <p>If I execute the function, it throws an error:</p>
  
  <pre><code> data &lt;- data.frame(c1 = c(1,5,3,2,1,7,7,7,6,5), c2 = 0.3*c(1:10), c3 = 0.5*c(1:10)+rnorm(10), c4 = 0.1*rnorm(10))
   remodel_vif(data,2.0)
  </code></pre>
  
  <p><code>Error in model.matrix.default(mt, mf, contrasts) : 
    model frame and formula mismatch in model.matrix()</code></p>
  
  <p>However, if I make this change in the function: </p>
  
  <pre><code>new_df &lt;- mdl$model %&gt;% dplyr::select(.,-bad_x) %&gt;% as.matrix() %&gt;% as.data.frame()
  </code></pre>
  
  <p>then it works:</p>
  
  <pre><code>&gt; remodel_vif(lm(data),2)
  
  Call:
  lm(formula = new_df)
  
  Coefficients:
  (Intercept)           c4  
        2.700        4.268  
  </code></pre>
  
  <p>Note: I'm aware this function doesn't make much sense and isn't very useful - I'm just wondering what causes the error to appear, and why transforming it back and forth like that helps.</p>
  
  <p>I found a <a href="https://stackoverflow.com/questions/28399090/r-how-to-update-model-frame-after-reducing-model-formula">similar question</a> here on SE, but I don't see how it's relevant: I'm not using the original model object's parameters - I only extract its underlying data frame and modify it. I don't see how there could be any interactions from the removed variables hanging around...</p>