Apply function to complex subset in data.table
<p>I'm new to <code>data.table</code> and I'd like to get better as I enter the realm of truly big datasets.</p>

<p>I'm trying calculate yearly means for a variable <code>x</code>, but from Jun (year y -1) to Jun (year y). This is easy using <code>plyr</code>:</p>

<pre><code>set.seed(9)

dat = data.frame(
  year = rep(2000:2010, each = 12),
  month = 1:12,
  x = runif(12*length(2000:2010))
)

library(plyr)

ldply(unique(dat$year), function(i) 

  if(i == unique(dat$year)[1]) NULL else # in the event going too far back

    data.frame(
      year = i,
      mean.x = mean(c(dat[dat$year == (i - 1) &amp; dat$month == 7:12, "x"], dat[dat$year == i &amp; dat$month == 1:6, "x"]))
    )

)
</code></pre>

<p>But I'm struggling to convert the syntax into <code>data.table</code>. I'd prefer to do it without creating an intermediate variable for year shifting everything 6 months forward, as there are some variables I would like to summarize in their original Jan-Dec framing.</p>

<p>Any help is appreciated! Cheers</p>