If we have multiple event outcomes as a long format like this (actual data contain many ids, this is a simplified data).
data <- data.frame(id=c(rep(1, 4), re
intervals = ave(
data$time,
data$id,
FUN = function(x)
c(0, diff(x))
)
intervals
# [1] 0 150 -100 150 0 160 -250 0 350 -500
meets_duration_requirement = ave(
intervals,
data$id,
FUN = function(x)
x >= 100 & x <= 150
) == 1 & data$event == 1
choose_second = meets_duration_requirement == 1 &
ave(meets_duration_requirement, data$id, FUN = seq_along) == 2 #if you want third event, change this to 3
replace(x = rep(NA, NROW(data)),
list = choose_second,
1)
# [1] NA 1 NA NA NA NA NA NA NA NA