To simplify, subset dat into the two Group entries; what will work for one will work for the other. That step is omitted below, because the value of Group does not change until the final row; if values alternate, the problem arises.
The condition test can be performed with dplyr::lag on Month with three tests:
Month - lag(Month,3) == 1 &
Month - lag(Month,2) == 1 &
Month - lag(Month,1) == 1
If all three conditions are met, Stability = lag(Value,1); else, NA
It will prove convenient to use a function for the test.
suppressPackageStartupMessages({library(dplyr)})
dat <- structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2), Month = c(
2,
4, 5, 6, 7, 10, 11, 12, 13, 14, 5
), Value = c(
0.1, 0.1, 0.1,
0.1, 0.2, 0.1, 0.1, 0.1, 0.2, 0.2, 0.3
)), class = "data.frame", row.names = c(
NA,
-11L
), codepage = 65001L)
do_test <- function(x) {
x - lag(x,3) == 3 &
x - lag(x,2) == 2 &
x - lag(x,1) == 1
}
dat %>% mutate(Stability = ifelse(do_test(Month) == TRUE,lag(Value,1),NA))
#> Group Month Value Stability
#> 1 1 2 0.1 NA
#> 2 1 4 0.1 NA
#> 3 1 5 0.1 NA
#> 4 1 6 0.1 NA
#> 5 1 7 0.2 0.1
#> 6 1 10 0.1 NA
#> 7 1 11 0.1 NA
#> 8 1 12 0.1 NA
#> 9 1 13 0.2 0.1
#> 10 1 14 0.2 0.2
#> 11 2 5 0.3 NA
Created on 2020-09-23 by the reprex package (v0.3.0.9001)
A similar lag approach will serve to detect 5 consecutive months.