How can I change values froma vector with a previous condition?

Viewed 64

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...

3 Answers

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

You can do :

#Copy vector1 elements
vector2 <- vector1
#Get indices where vector has TRUE elements
inds <- which(vector2)
#Get +1 and -1 position of each TRUE value
inds1 <- unique(c(inds + 1, inds -  1))
#Remove values which are out of range
inds1 <- inds1[inds1 <= length(vector2) & inds1 >= 1]
#Assign TRUE values
vector2[inds1] <- TRUE
vector2
#[1] FALSE  TRUE  TRUE  TRUE FALSE
Related