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

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

    Yet another approach. Create a set of lagged vectors, and or them together:

    library(Hmisc)
    library(functional)
    within.distance <- function(x, d=2) {
      FLag <- function(x, shift) {
        x <- Lag(x, shift)
        x[is.na(x)] <- FALSE
        return(x)
      }
    
      l <- lapply((-d):d, Curry(FLag, x=x))
      return(Reduce(`|`, l))
    }
    

提交回复
热议问题