I have a problem that I want to ask for your advice.
I am trying to compute "the duration of the previous month's Value in consecutive months" only when there are at least 3 months' of observations in the past.
An example data looks like:
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)
To clarify, the table below ("Stability" column) is what I am seeking. I added Note for the rationale of Stability:
╔═══════╦═══════╦═══════╦═══════════╦════════════════════════════════════════════════════════════╗
║ Group ║ Month ║ Value ║ Stability ║ Note ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 2 ║ 0.1 ║ na ║ Because there is no previous month's Value ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 4 ║ 0.1 ║ na ║ Because there is no previous month's Value ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 5 ║ 0.1 ║ na ║ We cannot know what happened for Month 3 ║
║ ║ ║ ║ ║ (Or there is no data for 3 consecutive months in the past) ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 6 ║ 0.1 ║ na ║ There is no 3 consecutive months' of data in the past ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 7 ║ 0.2 ║ 3 ║ 0.1 (Month 6's Value) was stable for 3 months in the past, ║
║ ║ ║ ║ ║ from Month 4 to 6 ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 10 ║ 0.1 ║ na ║ Because there is no previous month's Value ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 11 ║ 0.1 ║ na ║ There is no 3 consecutive months' of data in the past ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 12 ║ 0.1 ║ na ║ There is no 3 consecutive months' of data in the past ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 13 ║ 0.2 ║ 3 ║ 0.1 (Month 12's Value) was stable for 3 months in the past ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 1 ║ 14 ║ 0.2 ║ 1 ║ 0.2 (Month 13's Value) was stable for 1 month (Month 13) ║
╠═══════╬═══════╬═══════╬═══════════╬════════════════════════════════════════════════════════════╣
║ 2 ║ 5 ║ 0.3 ║ na ║ Because there is no previous month's Value for Group 2... ║
╚═══════╩═══════╩═══════╩═══════════╩════════════════════════════════════════════════════════════╝