jalapic - 8 months ago 33

R Question

Am I missing a better way of doing this - or at least a way that allows to vary the window size?

Say I have a vector, v.

`v <- c(T,T,F,F,F,F,F,T,T,T,T,F,F,F,F,T,F,F,F,F,F,F,T,F)`

I wish to convert this vector such that FALSEs are turned to TRUEs if a TRUE appeared within the previous 3 elements. e.g. the F's at positions 3,4,5 would also switch to T's as there is a T at position 2. The F at position 6 would not.

Solution if only interested in a window of 3:

`vlag1 <- lag(v)`

vlag2 <- lag(vlag1)

vlag3 <- lag(vlag2)

ifelse(v==T|vlag1==T|vlag2==T|vlag3==T,T,F)

Gives the desired result:

`TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE TRUE`

But what if we wanted to vary the window to e.g. 4 or 5 - is there a better way?

Answer

Here is one option with `data.table`

```
library(data.table)
n <- 3
r1 <- Reduce(`|`, shift(v, seq_len(n), fill = FALSE))
identical(r1, r2)
#[1] TRUE
```

where 'r2' is the OP's output from `ifelse`

Source (Stackoverflow)