Instead of using lead
and lag
you can use rolling operations which can be adapted easily if your window size increases/decreases.
library(dplyr)
library(zoo)
df %>%
mutate(result1 = lag(rollapplyr(BP, 4, function(x)
paste0(rev(x), collapse = ''), fill = NA)),
result2 = rollapply(BP, 2, align = 'left', function(x)
paste0(rev(x), collapse = ''), fill = NA))
# ID BP result1 result2
#1 Id1 A <NA> AA
#2 Id2 A <NA> TA
#3 Id3 T <NA> CT
#4 Id4 C <NA> AC
#5 Id5 A CTAA TA
#6 Id6 T ACTA AT
#7 Id7 A TACT TA
#8 Id8 T ATAC <NA>
Suggestion by @G. Grothendieck avoids the above hacky way with rev
and lag
.
df %>%
mutate(result11 = rollapply(BP,list(-(1:4)), paste, collapse = '', fill = NA),
result2 = rollapply(BP, list(1:2), paste, collapse = '', fill = NA))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…