title: How to calculate the time difference between two event in R?
body: <p>I have a question regarding an algorithm that I don't know how to solve.</p>
  
  <p>I have a dataset that looks like this:</p>
  
  <pre><code>Time Dose ID
  0     0   1
  0.1   1   1
  0.2   0   1
  0.3   0   1
  0.4   1   1
  0.5   0   1
  0.7   0   1
  0     0   2
  0.2   0   2
  0.3   1   2
  0.4   0   2
  0.6   0   2
  0.8   1   2
  0.9   0   2
  1.0   1   2
  1.5   0   2
  </code></pre>
  
  <p>There's many subjects in the dataset, with each subject dosed at different times. What I want to calculate is to calculate a column of data, which is the time after last dose for each subject. Since each subject is dosed several times, how do I update the number of time subtracted from the R program? Thank you!</p>
  
  <p>The expected look would be:</p>
  
  <pre><code>Time Dose ID TPD
  0     0   1   0
  0.1   1   1   0
  0.2   0   1   0.1
  0.3   0   1   0.2
  0.4   1   1   0
  0.5   0   1   0.1
  0.7   0   1   0.3
  0     0   2   0
  0.2   0   2   0.2
  0.3   1   2   0
  0.4   0   2   0.1
  0.6   0   2   0.3
  0.8   1   2   0
  0.9   0   2   0.1
  1.0   1   2   0
  1.5   0   2   0.5
  </code></pre>