title: How to calculate the total time duration of concentration crossing a threshold multiple times?
body: <p>Using R, I am trying to calculate the total time duration for each individual where this time duration is the time spent above certain threshold. </p>
  
  <p>For example, in the plot below I have the concentration data for 3 subjects (ID), and I would like to find the time (x axis) spent above the blue dashed line for each individual. the data set structure would be something like:</p>
  
  <pre><code>head(dataset)
    ID time      CP
  1  1  0.0 0.00000000
  2  1  0.0 0.00000000
  3  1  0.5 0.03759806
  4  1  1.0 0.12523455
  5  1  1.5 0.23483219
  6  1  2.0 0.34820905
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/uPim2.png" rel="noreferrer"><em>Solid lines represent the concentrations for 3 different subjects</em></a></p>
  
  <p>I tried to use the following code:</p>
  
  <pre><code>library(data.table) 
  TAbove&lt;-setDT(dataset)[CP &gt; .05, diff(range(time)), by = ID]
  </code></pre>
  
  <p>However,  this code that it calculates the time duration from first rise above dashed blue line to the last drop. For example for the green line ID, see the black line.</p>
  
  <p><a href="https://i.stack.imgur.com/uPim2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uPim2.png" alt="enter image description here"></a></p>
  
  <p>How can I write a code that takes into account the times where the concentrations drop below the dashed line, by excluding them. the final result would be a total time duration of all the times above the dashed blue line. like below</p>
  
  <p><a href="https://i.stack.imgur.com/ZLU7i.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZLU7i.png" alt="enter image description here"></a></p>