title: R (dplyr): count number of "0" observations before "1" in a column by ID
body: <p>I have a dataset with two variables: <code>ID</code>, <code>repeatvisit</code>, and <code>timeperiod</code>. <code>ID</code> represents the individual that visits the clinic, while <code>referredvisit</code> represents whether that observation has been recommended a referral. In other words, <code>referredvisit == 0</code> means that the individual is not referred to go to another clinic, while <code>referredvisit == 1</code> represents a patient that is recommended a referral. <code>timeperiod</code> shows the sequence in which the individuals come in. </p>
  
  <p>My dataset looks like this: </p>
  
  <pre><code>timeperiod &lt;- 1:18
  ID &lt;- c("TOM", "TOM", "SALLY", "SALLY", "RICHIE", "TOM", "TOM", "SALLY", "RICHIE", "RICHIE", "RICHIE", "SALLY", "TOM", "TOM", "TOM", "RICHIE", "RICHIE", "RICHIE")
  referredvisit &lt;- c(0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0)
  df &lt;- cbind(timeperiod, ID, referredvisit)
  df &lt;- as.data.frame(df)
  </code></pre>
  
  <p>What I aim to do is to for every <code>referredvisit == 0</code>, I would like to count how many rows of <code>"1"s</code> preceded it until it hits the beginning of the column (for the first 0) or until it hits another 0 (for the rest of the 0s) by ID. I want to create a column that store this count. My result for the dataset should look like this: </p>
  
  <pre><code>df$result &lt;- c(0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 1, 0, 2, 0)
  </code></pre>
  
  <p>I am actually trying to follow this <a href="https://stackoverflow.com/questions/38062796/count-number-of-rows-until-a-value-is-reached" title="link">link</a>, but it can't seem to work as the link assumes that the ID is nicely sorted out. I was thinking that perhaps <code>dplyr</code> might help, but can't seem to figure something out too. Deeply appreciate if anyone could help me in this! </p>
  
  <p>Thank you in advance!</p>
  
  <p>EDIT: For better visualisation, the result will look like this. But this is only after I manually sort it by ID. Cause my original data set will contain thousands of rows, and it is difficult for me to sort the ID manually. <br/>
  <a href="https://i.stack.imgur.com/sNsI9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sNsI9.jpg" alt="enter image description here"></a></p>