jalapic - 1 year ago 63
R Question

# Finding if values exists in previous n values of vector r

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?

Here is one option with `data.table`
``````library(data.table)
where 'r2' is the OP's output from `ifelse`