title: How to use cummean based on a condition in dplyr
body: <p>I'm trying to calculate the cumulative mean of a column in my data frame, but I only want it to be done based on a condition. </p>
  
  <pre><code>data &lt;- data.frame(col1 = c("A","A","B","B","A"),
                     col2 = c(1,0,1,0,1))
  </code></pre>
  
  <p>Lets say I want to calculate <code>col3</code> as the <code>cummean</code> of <code>col2</code> but only if <code>col1 = "A"</code> </p>
  
  <p>Expected output should be </p>
  
  <pre><code>A 1 1.00
  A 1 0.50
  B 1 NA
  B 0 NA
  A 1 0.67
  </code></pre>
  
  <p>Ideally it would be nice if the NA values picked up the <code>lag</code> value of cummean as a default. Something like </p>
  
  <pre><code>A 1 1.00
  A 1 0.50
  B 1 0.50
  B 0 0.50
  A 1 0.67
  </code></pre>
  
  <p>I was trying out <code>mutate_if</code> but couldn't quite work out the right syntax. Perhaps the answer should be <code>cummean</code> inside an <code>ifelse</code> with a regular <code>mutate</code>. Not sure what's the best way to approach. Any help hugely appreciated. Thank you!</p>