title: Adding AR(1) term to multiple regressions in R
body: <p>I am running 503 separate regressions, each with a separate dependent variables, with 3 independent variables and 1 AR(1) term. </p>
  
  <p><strong>Data:</strong></p>
  
  <pre><code># fake data 
  set.seed(333)
  df &lt;- data.frame(seq(as.Date("2017/1/1"), as.Date("2017/2/19"), "days"),
                   matrix(runif(50*506), nrow = 50, ncol = 506))
  
  names(df) &lt;- c("Date", paste0("var", 1:503), c("mktrf", "smb", "hml"))
  </code></pre>
  
  <p>I create the AR(1) process as follows, using a function called lagpad:</p>
  
  <pre><code>lagpad &lt;- function(x, k=1) {
    i&lt;-is.vector(x)
    if(is.vector(x)) x&lt;-matrix(x) else x&lt;-matrix(x,nrow(x))
    if(k&gt;0) {
      x &lt;- rbind(matrix(rep(NA, k*ncol(x)),ncol=ncol(x)), matrix(x[1:(nrow(x)-k),], ncol=ncol(x)))
    }
    else {
      x &lt;- rbind(matrix(x[(-k+1):(nrow(x)),], ncol=ncol(x)),matrix(rep(NA, -k*ncol(x)),ncol=ncol(x)))
    }
    if(i) x[1:length(x)] else x
  }
  </code></pre>
  
  <p>Then I store my necessary variables for regression:</p>
  
  <ol>
  <li><p><strong>All the dep var</strong></p>
  
  <pre><code>x = df[,505:507]
  </code></pre></li>
  <li><p><strong>All the indep var</strong></p>
  
  <pre><code>y &lt;- df[,2:504]
  </code></pre></li>
  <li><p><strong>AR(1) process</strong></p>
  
  <pre><code>y_lag &lt;- lagpad(y, -1)
  </code></pre></li>
  <li><p><strong>Fit all the models</strong></p>
  
  <pre><code>list_models_AR= lapply(y, function(y) 
         with(x, lm(y ~ mktrf +  smb + hml + y_lag, na.action = na.exclude)))
  </code></pre></li>
  </ol>
  
  <p>I'm having trouble figuring out how to use <code>lapply</code> in this case, since there are multiple components of <em>y_lag</em> that need to be called, one for each regression. </p>