I'd like to count the number of num that don't equal the previous num within the past d days, preferably with data.table.
My data looks like this:
d <- 3
df1 <- structure(list(LET = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L),
.Label = c("a", "b"), class = "factor"),
day = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L),
num = c(5, 6, 6, 7, 7, 1, 1, 3, 1, 1)),
class = c("data.table", "data.frame"),
row.names = c(NA, -10L))
LET day num
1: a 1 5
2: a 2 6
3: a 3 6
4: a 4 7
5: a 5 7
6: b 1 1
7: b 2 1
8: b 3 3
9: b 4 1
10: b 5 1
And I can use shift to say whether or not a num equals its lagged value, whether or not a num has changed:
df1[,hasChanged := num!=shift(num, n=1, fill=FALSE), by='LET']
But I'd like to count the number of num changes where day <= currentRowDay & day > currentRowDay - d , by LET.
Output would look like this (hasChanged column is optional):
df1[,NumberOfChangesPast3Days := c(1,2,2,2,1,1,1,2,2,2),]
LET day num hasChanged NumberOfChangesPast3Days
1: a 1 5 TRUE 1
2: a 2 6 TRUE 2
3: a 3 6 FALSE 2
4: a 4 7 TRUE 2
5: a 5 7 FALSE 1
6: b 1 1 TRUE 1
7: b 2 1 FALSE 1
8: b 3 3 TRUE 2
9: b 4 1 TRUE 2
10: b 5 1 FALSE 2