这是另一个尝试。它似乎适用于您的数据,并且当第一个元素为 TRUE 时也是如此。
as.logical(rowSums(embed(c(FALSE, FALSE, v, FALSE, FALSE), 5)))
# [1] FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
# another attempt with beginning and end TRUE
v = c(T, F, F, F, F, F, T, F, F, F, F, F, T)
# [1] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE
类似于@flodel 的想法,可以在这里创建一个函数:
rollOR <- function(vec, dir="both", dist=2) {
stopifnot(dir %in% c("left", "right", "both"))
stopifnot(dist >= 0)
stopifnot(is.logical(vec))
cvec <- rep(FALSE, dist)
switch(dir,
both = {
vec <- c(cvec, vec, cvec)
dist <- dist * 2 + 1
},
left = {
vec <- c(vec, cvec)
dist <- dist + 1
},
right = {
vec <- c(cvec, vec)
dist <- dist + 1
})
as.logical(rowSums(embed(vec, dist)))
}
# direction both sides
rollOR(v, "both", 2)
# [1] FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
# left alone
rollOR(v, "left", 2)
# [1] FALSE TRUE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE
# right alone
rollOR(v, "right", 2)
# [1] FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE