How to calculate the average exposure for intervals in another dataframe

Viewed 25

I need to calculate the average exposure for intervals above 0 of a dataset. I have already find the peaks with the pracma::findpeaks() function and have the information in a dataset. Now I would like to get the average exposure for those intervals, but I don't know how to do it.

An example of the data is:

time_initial <- seq(from = as.POSIXct("08:19:00", "%H:%M:%S", tz="UTC"), to = as.POSIXct("08:19:59", "%H:%M:%S", tz="UTC"), by = "1 sec")
time_min <- format(as.POSIXct(time_initial), format = '%H:%M:%S')
exposure <- c(0,0,2,3,5,0,0,4,5,6,0,0,0,0,0,0,4,5,0,0)
data <- as.data.frame(cbind(time_min, exposure))

An example of the peak information is:

data$exposure <- as.numeric(data$exposure)
peak <- findpeaks(data$exposure, nups = 0, ndowns = 0, minpeakheight = 1, sortstr = FALSE, threshold = 1, npeaks = 3)

peak_info <- data.frame(
  peak_number = 1:nrow(peak),
  time_peak_max = data[peak[,2],"time_min"],
  peak_heigth = data[peak[,2],"exposure"],
  peak_start = data[peak[,3],"time_min"],
  peak_end = data[peak[,4],"time_min"])

I would like to get the average of exposure (from dataset data) for the intervals between peak_start and peak_end (from dataset peak_info).

Many thanks

1 Answers

An option is to convert the time columns to ITime class with as.ITime and then do a non-equi join with data.table

library(data.table)
setDT(data)[, time_min := as.ITime(time_min)]
setDT(peak_info)[, c("peak_start", "peak_end") := lapply(.SD, as.ITime), 
     .SDcols = c("peak_start", "peak_end")]
data[peak_info, .(MeanExposure = mean(exposure, na.rm = TRUE)),
    on = .(time_min >= peak_start, time_min <= peak_end), by = .EACHI]

-output

   time_min time_min MeanExposure
    <ITime>  <ITime>        <num>
1: 08:19:01 08:19:05         2.00
2: 08:19:06 08:19:10         3.00
3: 08:19:15 08:19:18         2.25
Related