I have a logical vector
vector1 <- c(F,F,T,F,F)
and I want to create a vector2 with the same values as vector1 but when vector1[i] == TRUE vector2[i-1], vector2[i] and vector2[i+1] has to be also TRUE.
What is the best way to do this? the ideal would be to create a function also since I will have to this for many other vectors...
One way using boolean comparison is:
c(vector1[-1], FALSE) | vector1 | c(FALSE, vector1[-length(vector1)])
Value is TRUE at a position if the preceding is TRUE, or the position is TRUE or the next position is TRUE. First and last values are boundaries and have no preceding or next values, that is why positions are completed by FALSE.
For more than one position, here two:
lag <- 2
c(vector1[-(1:lag)], rep(FALSE, lag)) | vector1 | c(rep(FALSE, lag), vector1[-(length(vector1)-lag+1:length(vector1))])
[1] TRUE FALSE TRUE FALSE TRUE
You can also try dplyr:
case_when(lead(vector1) ~ TRUE,
lag(vector1) ~ TRUE,
TRUE ~ vector1)
[1] FALSE TRUE TRUE TRUE FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With