title: Generating mean column calculated over a time window defined by a categorical variable in R
body: <p>I have a data frame which looks like this:</p>
  
  <pre><code>structure(list(week  = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 
                 freq  = c(0, 4.34, 1.24, 0, 5.26, 0, 7.12, 3.70, 0, 0), 
                 event = c(0, 0, 0, 0, 0, 0, 1, 0, 0, 0)), 
            row.names = c(NA, -10L), 
            class = c("tbl_df", "tbl", "data.frame"))
  </code></pre>
  
  <p>What I need to do is to create a new column calculating, in correspondence of event=1, the average of freq for the window between -2 and -4 previous weeks, identified by the variable week.
  For instance, since event=1 at week 7, I would like to average freq for weeks 2, 3, 4 and 5. This has to be repeated every time event is equal to 1. That mean value should be reported in the new column in the row where event=1. </p>
  
  <p>Similarly, I will need to generate another column with the mean of window -1 ; +2 with respect to event=1, so in this case weeks 6 to 9. </p>
  
  <p>The final result should look like this:</p>
  
  <pre><code>week    freq    event     mean1     mean2
  1       0       0         NA        NA
  2       4.34    0         NA        NA
  ...
  7       7.12    1         2.71      2.705
  ...
  </code></pre>
  
  <p>I would be grateful if you could help me on this, I've read several similar threads but I couldn't find a solution to this specific problem.</p>