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

前端 未结 4 391
终归单人心
终归单人心 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:34

    This sort of thing is probably as vectorized as you're going to get:

    v[unlist(sapply(which(v),function(x) {x + c(-2,-1,1,2)},simplify = FALSE))] <- TRUE
    > v
     [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
    

    But note that you haven't specified what should happen in the TRUE elements are near the ends of your vector. That would require more work. Nor do you specify what happens if there are two TRUE elements that are closer than two positions from each other.

    Alternatively:

    v[outer(which(v),c(-2,-1,1,2),"+")] <- TRUE
    > v
     [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
    

    At a basic level, we're doing the same thing here, but the second option is certainly more compact, although possibly harder to understand.

提交回复
热议问题