Q:

How to find the next k values groupwise in R?

The data is 
row group id value
1   a     1  TRUE
2   a     2  FALSE
3   a     3  FALSE
4   a     4  FALSE
5   b     5  TRUE
6   b     6  FALSE
7   b     7  TRUE

I want to have a new column i so that if any value of this row and the next two rows (in the same group) is TRUE, i is TRUE, otherwise i is FALSE. 
So the result I want to see is 
row group id value i
1   a     1  TRUE  TRUE
2   a     2  FALSE FALSE
3   a     3  FALSE FALSE
4   a     4  FALSE FALSE
5   b     5  TRUE  TRUE
6   b     6  FALSE TRUE
7   b     7  TRUE  TRUE

Thank you for help!

A:

You can use zoo::rollapply with ave as the grouping function; By default, rollapply gives n+1-window_size elements, in order to calculate the tail elements correctly, you can align the result to the left and specify partial is TRUE so that window less than the specified window size can also be calculated:
library(zoo)
df$i <- with(df, ave(value, group, FUN=function(x) rollapply(x, 3, any, partial=T, align="left")))
df

#  row group id value     i
#1   1     a  1  TRUE  TRUE
#2   2     a  2 FALSE FALSE
#3   3     a  3 FALSE FALSE
#4   4     a  4 FALSE FALSE
#5   5     b  5  TRUE  TRUE
#6   6     b  6 FALSE  TRUE
#7   7     b  7  TRUE  TRUE

