title: Find the variance over a sliding window in dplyr
body: <p>I want to find the variance of the previous three values in a group.</p>
  
  <pre><code># make some data with categories a and b
  library(dplyr)
  df = expand.grid(
    a = LETTERS[1:3],
    index = 1:10
  )
  # add a variable that changes within each group
  set.seed(9999)
  df$x = runif(nrow(df))
  
  # get the variance of a subset of x
  varSubset = function(x, index, subsetSize) {
    subset = (index-subsetSize+1):index
    ifelse(subset[1]&lt;1, -1, var(x[subset]))
  }
  
  df %&gt;%
    # group the data
    group_by(a) %&gt;%
    # get the variance of the 3 most recent values
    mutate(var3 = varSubset(x, index, 3))
  </code></pre>
  
  <p>It's calling the <code>varSubset</code> with both <code>x</code> and <code>index</code> as vectors.</p>
  
  <p>I can't figure out how to treat <code>x</code> as a vector (of only the group) and <code>index</code> as a single value. I've tried <code>rowwise()</code>, but then I effectively lose grouping.</p>