title: Calculating the difference between two values in the same column by ID based one the value of another column in R
body: <p>I have a dataset that looks like this:</p>
  
  <pre><code>threadid    unixtime    sent    ID  
  123         1000        0       1   
  123         1050        1       1   
  123         1070        0       1   
  123         2000        1       1   
  123         2500        1       1   
  123         3000        0       1   
  123         1000        0       2   
  123         1500        0       2   
  123         2500        1       2  
  </code></pre>
  
  <p>But I want it to look like this:</p>
  
  <pre><code>threadid    unixtime    sent    ID  change
  123         1000        0       1   
  123         1050        1       1   
  123         1070        0       1   
  123         2000        1       1   
  123         2500        1       1   1430
  123         3000        0       1   
  123         1000        0       2   
  123         1500        0       2   
  123         2500        1       2   1000
  </code></pre>
  
  <p>So by ID, I want to look for the last occurrence of a "1" and then calculate the time difference between the unix time that corresponds with the 1 and the previous observation (or last observation with a 0 in the "sent" column) that has 0 in the "sent" column. I think this may involve a "for" loop but I've tried a lot of things and just can't quite get it. Any help is greatly appreciated!</p>