Я думаю, что данных вашего примера недостаточно, чтобы показать все случаи, но обычно это следует делать:
Date <- c(rep(as.Date("2010/12/14"), 4), rep(as.Date("2011/01/13"), 4), rep(as.Date("2011/02/10"), 4),rep(as.Date("2011/03/10"), 4))
dummy <- rep(1, 16)
Name <- c("A","B","C","D","A","C","F","G","A","B","F","H","A","F","H","I")
df <- data.frame(Date, Name, dummy)
le = LETTERS[1:9]
temp = CJ(Name=le, Date=unique(Date))
df = data.table(df)
setkey(df, Name, Date)
setkey(temp, Name, Date)
df = df[temp]
df[,value:=case_when(dummy==1 & shift(dummy, type = "lag", n = 1)==1 & shift(dummy, type = "lag", n = 2)==1 ~ 0,
dummy==0 & shift(dummy, type = "lag", n = 1)==1 & shift(dummy, type = "lag", n = 2)==1 ~ 1,
dummy==1 & shift(dummy, type = "lag", n = 1)==1 & shift(dummy, type = "lag", n = 2)==0 ~ 1,
dummy==0 & shift(dummy, type = "lag", n = 1)==1 & shift(dummy, type = "lag", n = 2)==0 ~ 2,
TRUE~88), by=Name][dummy==1]