title: Adding lagged variables to an lm model?
body: <p>I'm using lm on a time series, which works quite well actually, and it's super super fast.</p>
  
  <p>Let's say my model is:</p>
  
  <pre><code>&gt; formula &lt;- y ~ x
  </code></pre>
  
  <p>I train this on a training set:</p>
  
  <pre><code>&gt; train &lt;- data.frame( x = seq(1,3), y = c(2,1,4) )
  &gt; model &lt;- lm( formula, train )
  </code></pre>
  
  <p>... and I can make predictions for new data:</p>
  
  <pre><code>&gt; test &lt;- data.frame( x = seq(4,6) )
  &gt; test$y &lt;- predict( model, newdata = test )
  &gt; test
    x        y
  1 4 4.333333
  2 5 5.333333
  3 6 6.333333
  </code></pre>
  
  <p>This works super nicely, and it's really speedy.</p>
  
  <p>I want to add lagged variables to the model.  Now, I could do this by augmenting my original training set:</p>
  
  <pre><code>&gt; train$y_1 &lt;- c(0,train$y[1:nrow(train)-1])
  &gt; train
    x y y_1
  1 1 2   0
  2 2 1   2
  3 3 4   1
  </code></pre>
  
  <p>update the formula:</p>
  
  <pre><code>formula &lt;- y ~ x * y_1
  </code></pre>
  
  <p>... and training will work just fine:</p>
  
  <pre><code>&gt; model &lt;- lm( formula, train )
  &gt; # no errors here
  </code></pre>
  
  <p>However, the problem is that there is no way of using 'predict', because there is no way of populating y_1 in a test set in a batch manner.</p>
  
  <p>Now, for lots of other regression things, there are very convenient ways to express them in the formula, such as <code>poly(x,2)</code> and so on, and these work directly using the unmodified training and test data.</p>
  
  <p>So, I'm wondering if there is some way of expressing lagged variables in the formula, so that <code>predict</code> can be used?  Ideally:</p>
  
  <pre><code>formula &lt;- y ~ x * lag(y,-1)
  model &lt;- lm( formula, train )
  test$y &lt;- predict( model, newdata = test )
  </code></pre>
  
  <p>... without having to augment (not sure if that's the right word) the training and test datasets, and just being able to use <code>predict</code> directly?</p>