title: How to handle null subsets in R (dplyr)
body: <p>I wish to calculate the average volume per group by sub-setting my data frame between two date ranges.</p>
  <p>I have noticed that not all products have records between these two dates and need some way to handle these as right now they are captured as blanks, ideally these would be filled with 0 rather than blanks.</p>
  <p>Here is a reprex:</p>
  <pre><code>product &lt;- c(&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;C&quot;)
  date1 &lt;- c(&quot;2020-06-20&quot;,&quot;2020-06-26&quot;,&quot;2020-08-20&quot;,&quot;2020-08-22&quot;,&quot;2020-06-26&quot;,&quot;2020-06-27&quot;,&quot;2020-08-21&quot;,&quot;2020-08-22&quot;,&quot;2019-06-20&quot;)
  winA_start &lt;- rep(&quot;2020-06-24&quot;, times = 9)
  winA_end &lt;- rep(&quot;2020-06-30&quot;, times = 9)
  winB_start &lt;- rep(&quot;2020-08-19&quot;, times = 9)
  winB_end &lt;- rep(&quot;2020-08-26&quot;, times = 9)
  vol &lt;- c(200,201,600,800,800,1000,50,100,208)
  x &lt;- data.frame(product,date1,winA_start,winA_end,winB_start,winB_end,vol)
  x[,2:6] &lt;- lapply(x[,2:6], as.Date)
  </code></pre>
  <p>I wish to run the following code to calculate the average value for both Window A and Window B</p>
  <pre><code>y &lt;- x %&gt;% group_by(product) %&gt;% mutate(WIN_A_AVG = round(mean(vol[date1 &gt;= winA_start &amp; date1 &lt;= winA_end]), digits = 0), WIN_B_AVG = round(mean(vol[date1 &gt;= winB_start &amp; date1 &lt;= winB_end]), digit = 0))
  </code></pre>
  <p>This works as desired except for Product C where date1 does not meet the criteria and it therefore returns NaN.</p>
  <p>Rather than return NaN is there a way I could catch these type of errors and just return 0 in an elegant way?</p>
  <p><a href="https://i.stack.imgur.com/UDeUO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UDeUO.png" alt="enter image description here" /></a></p>