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
TAbove<-setDT(dataset)[CP > .05, diff(range(time)), by = ID]
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))