Malek Ik - 1 year ago 89
R Question

# How to calculate the total time duration of concentration crossing a threshold multiple times?

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.

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:

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

Solid lines represent the concentrations for 3 different subjects

I tried to use the following code:

library(data.table)
TAbove<-setDT(dataset)[CP > .05, diff(range(time)), by = ID]

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.

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

So, thanks to rhole for providing the idea of how to solve the question. the code below helped me do the analysis, however I had to add a variable called "Day", and then calculate the time duration per day. Here I used day because there is one interval per day. But you can adjust it according to your need.

#sub-setting by day
dataset\$Day[dataset\$time>=0 &dataset\$time<24] <- "Day 1"
dataset\$Day[dataset\$time>=24 &dataset\$time<48] <- "Day 2"
dataset\$Day[dataset\$time>=48 &dataset\$time<72] <- "Day 3"
#per day#
TAbove<-setDT(dataset)[CP > .05, diff((time)), by = .(ID,Day)]
library(plyr)
# sum the time duration for each day per person
sumPerDay<-summarise(group_by(TAbove, ID,Day),
sum=sum(V1))
# sum the time duration for ALL days per person
sumAll<-summarise(group_by(TAbove, ID),
sum=sum(V1))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download