title: Calculate Mean for Each Unique Value up to a certain date
body: <p>Data for my example.</p>
  <pre><code>date1 = seq(as.Date(&quot;2019/01/01&quot;), by = &quot;month&quot;, length.out = 48)
  date2 = seq(as.Date(&quot;2019/02/01&quot;), by = &quot;month&quot;, length.out = 48)
  date3 = seq(as.Date(&quot;2019/02/01&quot;), by = &quot;month&quot;, length.out = 48)
  date4 = seq(as.Date(&quot;2019/02/01&quot;), by = &quot;month&quot;, length.out = 48)
  date = c(date1,date2,date3,date4)
  
  
  
  subproducts1=rep(&quot;1&quot;,48)
  subproducts2=rep(&quot;2&quot;,48)
  subproductsx=rep(&quot;x&quot;,48)
  subproductsy=rep(&quot;y&quot;,48)
  
  b1 &lt;- c(rnorm(48,5))
  b2 &lt;- c(rnorm(48,5))
  b3 &lt;-c(rnorm(48,5) )
  b4 &lt;- c(rnorm(48,5))
  
  dfone &lt;- data.frame(
                  &quot;date&quot;= date,
                 
                  &quot;subproduct&quot;= 
                    c(subproducts1,subproducts2,subproductsx,subproductsy),
                  &quot;actuals&quot;= c(b1,b2,b3,b4))
  </code></pre>
  <p>This creates Jan 2019 for date2,3,4 with value 0.</p>
  <pre><code> dfone &lt;-dfone %&gt;%
   complete(date = seq.Date(from = min(date), to = as.Date('2021-06-01'), by = 'month'), 
         nesting(subproduct), fill = list(actuals = 0))
  </code></pre>
  <p>QUESTION: This calculates the mean for each unique sub product and replaces 0's with the mean of each, but how do I have a hard cutoff so the mean is only based off Jan-2019 to Dec-2020 and not Jan 2019 to Dec 2022?</p>
  <pre><code>library(dplyr)
  dfone_new &lt;- dfone %&gt;%
       group_by(subproduct)  %&gt;%
       mutate(actuals = replace(actuals, actuals == 0, 
           mean(actuals[actuals != 0], na.rm = TRUE))) %&gt;%
       ungroup
  </code></pre>