Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 864
João Machado Avatar asked Jan 01 '23 06:01

João Machado


2 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
like image 97
Clemsang Avatar answered May 12 '23 18:05

Clemsang


You can also try dplyr:

case_when(lead(vector1) ~ TRUE,
          lag(vector1) ~ TRUE,
          TRUE ~ vector1)

[1] FALSE  TRUE  TRUE  TRUE FALSE
like image 32
tmfmnk Avatar answered May 12 '23 18:05

tmfmnk