How can I vectorize access to neighbour vector elements in R?

前端 未结 4 441
终归单人心
终归单人心 2021-02-04 14:08

I have the following vector

 v = c(F, F, F, T, F, F, F, F, F, T, F, F, F)

How can I change v so that the previous 2 elements and the following

4条回答
  •  情话喂你
    2021-02-04 14:14

    Late to the party... You should apply a convolution filter. It will be faster than anything. The only difficulty is that at both extremities you should prepend/append a couple FALSE so the filter won't initialize with NAs. Here is a function that will do it for you:

    within.distance <- function(x, d = 2) {
        xxx  <- c(rep(FALSE, d), x, rep(FALSE, d))
        yyy  <- as.logical(filter(xxx, rep(1, 2*d+1)))
        head(tail(yyy, -d), -d)
    }
    
    within.distance(v)
    #  [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE TRUE FALSE
    

提交回复
热议问题