I have the following vector
v = c(F, F, F, T, F, F, F, F, F, T, F, F, F)
How can I change v so that the previous 2 elements and the following
This sort of thing is probably as vectorized as you're going to get:
v[unlist(sapply(which(v),function(x) {x + c(-2,-1,1,2)},simplify = FALSE))] <- TRUE
> v
[1] FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
But note that you haven't specified what should happen in the TRUE elements are near the ends of your vector. That would require more work. Nor do you specify what happens if there are two TRUE elements that are closer than two positions from each other.
Alternatively:
v[outer(which(v),c(-2,-1,1,2),"+")] <- TRUE
> v
[1] FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
At a basic level, we're doing the same thing here, but the second option is certainly more compact, although possibly harder to understand.