Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm almost embarrassed to post this. I'm usually pretty good as these, but there's got to be a better way. </p> <p>This first uses <code>zoo</code>'s <code>as.yearmon</code> to get the dates in terms of just month and year, then reshapes it to get one column for each <code>id</code>/<code>class</code> combination, then fills in with zeros before, after, and for missing months, then uses <code>zoo</code> to get the rolling sum, then pulls out just the desired months and merges back with the original data frame.</p> <pre><code>library(reshape2) library(zoo) df$yearmon &lt;- as.yearmon(df$t) dfa &lt;- dcast(id + class ~ yearmon, data=df, value.var="count") ida &lt;- dfa[,1:2] dfa &lt;- t(as.matrix(dfa[,-c(1:2)])) months &lt;- with(df, seq(min(yearmon)-3/12, max(yearmon)+3/12, by=1/12)) dfb &lt;- array(dim=c(length(months), ncol(dfa)), dimnames=list(paste(months), colnames(dfa))) dfb[rownames(dfa),] &lt;- dfa dfb[is.na(dfb)] &lt;- 0 dfb &lt;- rollsumr(dfb,4, fill=0) rownames(dfb) &lt;- paste(months) dfb &lt;- dfb[rownames(dfa),] dfc &lt;- cbind(ida, t(dfb)) dfc &lt;- melt(dfc, id.vars=c("class", "id")) names(dfc)[3:4] &lt;- c("yearmon", "desired2") dfc$yearmon &lt;- as.yearmon(dfc$yearmon) out &lt;- merge(df,dfc) &gt; out id class yearmon t count desired desired2 1 1 A Feb 2010 2010-02-15 2 3 3 2 1 A Jan 2010 2010-01-15 1 1 1 3 1 B Apr 2010 2010-04-15 3 3 3 4 1 B Sep 2010 2010-09-15 4 4 4 5 2 A Jan 2010 2010-01-15 5 5 5 6 2 B Aug 2010 2010-08-15 7 13 13 7 2 B Jun 2010 2010-06-15 6 6 6 8 2 B Sep 2010 2010-09-15 8 21 21 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload