title: Conditional running count (cumulative sum) with reset in R (dplyr)
body: <p>I'm trying to calculate a running count (i.e., cumulative sum) that is conditional on other variables and that can reset for particular values on another variable.  I'm working in R and would prefer a <code>dplyr</code>-based solution, if possible.</p>
  
  <p>I'd like to create a variable for the running count, <code>cumulative</code>, based on the following algorithm:</p>
  
  <ul>
  <li>Calculate the running count (<code>cumulative</code>) within combinations of <code>id</code> and <code>age</code></li>
  <li>Increment running count (<code>cumulative</code>) by 1 for every subsequent <code>trial</code> where <code>accuracy = 0</code>, <code>block = 2</code>, and <code>condition = 1</code></li>
  <li>Reset running count (<code>cumulative</code>) to 0 for each <code>trial</code> where <code>accuracy = 1</code>, <code>block = 2</code>, and <code>condition = 1</code>, and the next increment resumes at 1 (not the previous number)</li>
  <li>For each <code>trial</code> where <code>block != 2</code>, or <code>condition != 1</code>, leave the running count (<code>cumulative</code>) as <code>NA</code></li>
  </ul>
  
  <p>Here's a minimal working example:</p>
  
  <pre><code>mydata &lt;- data.frame(id = c(1,1,1,1,1,1,1,1,1,1,1),
                   age = c(1,1,1,1,1,1,1,1,1,1,2),
                   block = c(1,1,2,2,2,2,2,2,2,2,2),
                   trial = c(1,2,1,2,3,4,5,6,7,8,1),
                   condition = c(1,1,1,1,1,2,1,1,1,1,1),
                   accuracy = c(0,0,0,0,0,0,0,1,0,0,0)
  )
  
  id  age block   trial   condition   accuracy
  1   1   1       1       1           0
  1   1   1       2       1           0
  1   1   2       1       1           0
  1   1   2       2       1           0
  1   1   2       3       1           0
  1   1   2       4       2           0
  1   1   2       5       1           0
  1   1   2       6       1           1
  1   1   2       7       1           0
  1   1   2       8       1           0
  1   2   2       1       1           0
  </code></pre>
  
  <p>The expected output is:</p>
  
  <pre><code>id  age block   trial   condition   accuracy    cumulative
  1   1   1       1       1           0           NA
  1   1   1       2       1           0           NA
  1   1   2       1       1           0           1
  1   1   2       2       1           0           2
  1   1   2       3       1           0           3
  1   1   2       4       2           0           NA
  1   1   2       5       1           0           4
  1   1   2       6       1           1           0
  1   1   2       7       1           0           1
  1   1   2       8       1           0           2
  1   2   2       1       1           0           1
  </code></pre>