title: Time series regression by group with Newey-West standard errors in R
body: <p>First, I apologize if this question has been answered already. This is my first post on stackoverflow.</p>
  
  <p>I have a panel of stock market data that is structured as in this working example:</p>
  
  <pre><code>d &lt;- data.frame(Time = rep(seq.Date( Sys.Date(), length=10, by="day" )),
      Stock = rep(LETTERS[1:3], each=10 ),
      x1 = rep(sample(10:30, 10), 3),
      x2 = rep(sample(10:30, 10), 3),
      x3 = rep(sample(10:30, 10), 3))
  </code></pre>
  
  <p>Basically I want to estimate a time series regression with x1 as the dependent variable and as regressors x3 and the lag and lead of x2. I want to perform this for each stock in the sample using Newey West standard errors.</p>
  
  <p>After going to several posts here, I’ve managed to come up with the following:</p>
  
  <p>since I'm working with time series and want to use lag and lead operators, I’ve read that I should use the <code>zoo</code> or <code>xts</code> format (I’ve chosen the <code>zoo</code> format because this is compatible with the <code>dyn$lm</code> function which I want to use):</p>
  
  <pre><code>d.z &lt;- zoo(data.matrix(d[-1]), d$Time)
  </code></pre>
  
  <p>Note that I transform the Stock column to numeric because the <code>zoo</code> package requires all numeric variables.</p>
  
  <p>However, this brings up an error message:</p>
  
  <pre><code>Warning message:
  In zoo(data.matrix(d[-1]), d$Time):some methods for “zoo” objects do not work 
  if the index entries in ‘order.by’ are not unique.
  </code></pre>
  
  <p>I figured this is no problem since ultimately I want to estimate regressions for each stock separately, which would resolve the problem. </p>
  
  <p>To this object I then want to estimate the regression in myLm for each stock.</p>
  
  <pre><code>myLm &lt;- function(formula,df) {
  temp.lm &lt;- dyn$lm(formula,data=df)
  temp.summ &lt;- summary(temp.lm)
  temp.summ$coefficients &lt;- unclass(coeftest(temp.lm, vcov. = NeweyWest))
  lmOut&lt;-data.frame(t(temp.summ$coefficients))
  return(lmOut)}
  </code></pre>
  
  <p>Using the <code>plyr</code> package I try to split up the function by stock: </p>
  
  <pre><code>outDf &lt;- ddply(d.z, "Stock", function(df)  myLm(x1 ~ lag(x2, -1) + lag(x2, +1) + x3, df))
  </code></pre>
  
  <p>Unfortunately, this brings up another error:</p>
  
  <pre><code>Error in eval.quoted(.variables, data) : 
  envir must be either NULL, a list, or an environment.
  </code></pre>
  
  <p>What am I doing wrong here?</p>