 <p>You can instead use <code>RcppRoll::roll_sum</code> which returns NA if the sample size(<code>n</code>) is less than the window size(<code>k</code>). </p> <pre><code>set.seed(1) dg$count = rpois(dim(dg)[1], 5) library(RcppRoll) library(dplyr) dg %&gt;% arrange(site,year,animal) %&gt;% group_by(site, animal) %&gt;% mutate(roll_sum = roll_sum(count, 2, align = "right", fill = NA)) # site year animal count roll_sum #1 Boston 2000 dog 4 NA #2 Boston 2001 dog 5 9 #3 Boston 2002 dog 3 8 #4 Boston 2003 dog 9 12 #5 Boston 2004 dog 6 15 #6 New York 2000 dog 4 NA #7 New York 2001 dog 8 12 #8 New York 2002 dog 8 16 #9 New York 2003 dog 6 14 #10 New York 2004 cat 2 NA </code></pre>