title: rolling regression with dplyr
body: <p>I have a dataframe of "date", "company" and "return", reproducible by the code below:</p>
  
  <pre><code>library(dplyr)
  n.dates &lt;- 60
  n.stocks &lt;- 2
  date &lt;- seq(as.Date("2011-07-01"), by=1, len=n.dates)
  symbol &lt;- replicate(n.stocks, paste0(sample(LETTERS, 5), collapse = ""))
  x &lt;- expand.grid(date, symbol)
  x$return &lt;- rnorm(n.dates*n.stocks, 0, sd = 0.05)
  names(x) &lt;- c("date", "company", "return")
  </code></pre>
  
  <p>With this dataframe, I can calculate the daily market average return and add that result into a new column "market.ret".</p>
  
  <pre><code>x &lt;- group_by(x, date)    
  x &lt;- mutate(x, market.ret = mean(x$return, na.rm = TRUE))
  </code></pre>
  
  <p>Now I want to group all my data by different companies (2 in this case).</p>
  
  <pre><code>x &lt;- group_by(x, company)
  </code></pre>
  
  <p>After doing this, I would like to fit "return" by "market.ret" and calculate the linear regression coefficient and store the slopes in a new column. If I want to do the fitting for the whole data set within a given company, then I can simply call lm():</p>
  
  <pre><code>group_by(x, company) %&gt;%
  do(data.frame(beta = coef(lm(return ~ market.ret,data = .))[2])) %&gt;%
  left_join(x,.)
  </code></pre>
  
  <p>However, I actually want to do the linear regression on a "rolling" basis, i.e. for each day separately over a 20-day trailing period. I want to use rollapply() but do not know how to pass two columns into the function. Any help or suggestion is greatly appreciated.</p>
  
  <p>Note: Below is the code that I used for calculating 20-day rolling standard deviation of returns which might be helpful:</p>
  
  <pre><code>sdnoNA &lt;- function(x){return(sd(x, na.rm = TRUE))}
  x &lt;- mutate(x, sd.20.0.d = rollapply(return, FUN = sdnoNA, width = 20, fill = NA))
  </code></pre>