title: Feeding new data into predict() for multiple regression?
body: <p>Assume I have have fit a regression model with multiple predictor variables in R, like in the following toy example:</p>
  
  <pre><code>n &lt;- 20
  x &lt;- rnorm(n)
  y &lt;- rnorm(n)
  z &lt;- x + y + rnorm(n)
  m &lt;- lm(z ~ x + y + I(y^2))
  </code></pre>
  
  <p>Now I have new date, consisting of x and y values, and I want to predict the corresponding z values:</p>
  
  <pre><code>x.new &lt;- rnorm(5)
  y.new &lt;- rnorm(5)
  </code></pre>
  
  <p><strong>Question:</strong> How should I best call predict to apply the fitted model to the new data?</p>
  
  <p>Here are a few things I tried, which do not work:</p>
  
  <p>Attempt 1. Trying to use the <code>x.new</code> and <code>y.new</code> as the columns of a new data frame:</p>
  
  <pre><code>&gt; predict(m, data=data.frame(x=x.new, y=y.new))
           1          2          3          4          5          6          7 
  -0.0157090  1.1667958 -1.3797101  0.1185750  0.7786496  1.7666232 -0.6692865 
           8          9         10         11         12         13         14 
   1.9720532  0.3514206  1.1677019  0.6441418 -2.3010431 -0.3228424 -0.2181511 
          15         16         17         18         19         20 
  -0.8883275  0.4549592 -1.0377040  0.1750522 -2.4542843  1.2250101 
  </code></pre>
  
  <p>This gave 20 values instead of 5, so cannot be right.</p>
  
  <p>Attempt 2: Maybe <code>predict</code> got confused because the <code>y^2</code> values were not supplied?  Try to use <code>model.frame</code> to provide data in the correct form.</p>
  
  <pre><code>&gt; predict(m, model.frame(~ x.new + y.new + I(y.new^2)))
           1          2          3          4          5          6          7 
  -0.0157090  1.1667958 -1.3797101  0.1185750  0.7786496  1.7666232 -0.6692865 
           8          9         10         11         12         13         14 
   1.9720532  0.3514206  1.1677019  0.6441418 -2.3010431 -0.3228424 -0.2181511 
          15         16         17         18         19         20 
  -0.8883275  0.4549592 -1.0377040  0.1750522 -2.4542843  1.2250101 
  Warning message:
  'newdata' had 5 rows but variables found have 20 rows 
  </code></pre>
  
  <p>Again, this results in 20 values (plus a warning), so cannot be right.</p>