'find index based on condition in data.table

I have data like this:

library(data.table)

dt1 <- data.table(
  id = 1,
  week = c( seq(1:260))
)
dt1[0:100, status := "A"][101:260, status := "B"]

dt2 <- data.table(
  id = 2,
  week = c( seq(1:260))
)
dt2[0:34, status := "A"][35:70, status := "B"][71:260, status := "A"]

dt3 <- data.table(
  id = 3,
  week = c( seq(1:260))
)
dt3[0:80, status := "A"][81:90, status := "B"][91:100, status := "A"][101:260, status := "B"]

data <- rbind(dt1,dt2,dt3)

I would like to find, for each unique id, the index before which a 52 week period has passed with at least 75% (39 weeks) with status=="B". I would want the following end product:

data_want <- data.table(
  id = c(1,3),
  week = c(153, 133)
)

For id 1, 52 weeks after 101 (the first row with status==B) is 153 and at least 75% of that period, status==B. And so on.

Any suggestions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source