R : how to get the rolling mean of a variable over the last few days but only at a given hour?
<p>Consider this</p>

<pre><code>time &lt;- seq(ymd_hms("2014-02-24 23:00:00"), ymd_hms("2014-06-25 08:32:00"), by="hour")
group &lt;- rep(LETTERS[1:20], each = length(time))
value &lt;- sample(-10^3:10^3,length(time), replace=TRUE)
df2 &lt;- data.frame(time,group,value)
str(df2)

&gt; head(df2)
                 time group value
1 2014-02-24 23:00:00     A   246
2 2014-02-25 00:00:00     A  -261
3 2014-02-25 01:00:00     A   628
4 2014-02-25 02:00:00     A   429
5 2014-02-25 03:00:00     A   -49
6 2014-02-25 04:00:00     A  -749
</code></pre>

<p>I would like to create a variable that contains, for each group, the <strong>rolling mean</strong> of <code>value</code></p>

<ul>
<li>over the last 5 days (not including the current observation)</li>
<li><strong>only</strong> considering observations that fall a<em>t the exact same hour</em> as the current observation.</li>
</ul>

<p>In other words:</p>

<p>At time <code>2014-02-24 23:00:00</code>, <code>df2['rolling_mean_same_hour']</code> contains the mean of the values of <code>value</code> observed at <code>23:00:00</code> during the last 5 days in the data (not including <code>2014-02-24</code> of course).</p>

<p>I would like to do that in either <code>dplyr</code> or <code>data.table</code>. I confess having no ideas how to do that.</p>

<p>Any ideas?</p>

<p>Many thanks!</p>