title: moving average by another column in tidyverse
body: <p>I'm trying to perform a moving average calculation with tidyverse, here is my data set:</p>
  <pre><code>library(tidyverse)
  
  test &lt;- tibble(sub = sample(c(&quot;A&quot;, &quot;B&quot;), 100, replace = T),
                 A = sample(100, replace = T),
                 B = rnorm(100))
  </code></pre>
  <p>sub is classification, A is coordinate and B is value for calculation.</p>
  <p>I want to calculate the moving average value based on coordinate, classification, window size and step size.
  for example, window size is 10 and step size is 2, the first window is [0, 10], the second window is [2, 12]...</p>
  <p>here is my solution:</p>
  <pre><code># find the max coordinate in each classification
  submax &lt;- test %&gt;%
    group_by(sub) %&gt;%
    summarise(maxA = max(A))
  # keep the last window
  windowsize &lt;- 10
  stepsize &lt;- 2
  seq_num &lt;- ceiling(submax$maxA/stepsize)
  # generate window dataframe
  wind.bin &lt;- tibble(sub = rep(submax$sub, seq_num),
                     num = map(seq_num, seq) %&gt;% unlist() - 1) %&gt;%
    group_by(sub) %&gt;%
    mutate(start = num*stepsize,
           end = num*stepsize + windowsize)
    select(sub, start, end)
  # join and average
  res &lt;- test %&gt;%
    inner_join(wind.bin, by = &quot;sub&quot;) %&gt;%
    filter(start &lt;= A &amp; A &lt;= end) %&gt;%
    group_by(sub, start, end) %&gt;%
    summarise(avg = mean(B))
  </code></pre>
  <p>The problem is that the intermediate file generated by inner_join is too large. Is there a more elegant way to achieve the same goal?</p>