For any binary vector x
, we can use the following logic to detect existing pattern of two adjacent 1:
flag <- function (x) sum(x == 1 & c(diff(x) == 0, FALSE)) > 0
x <- c(1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
flag(x)
#[1] TRUE
x <- c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0)
flag(x)
#[1] FALSE
So we can apply this to all columns of your data frame DF
:
sapply(DF, flag)
As r2evans commented, this also works:
flag <- function (x) any(x == 1 & c(diff(x) == 0, FALSE))
Using sum
gives you a by-product: it tells you the number of matches.
Gosh, you want to apply flag
for every row not every column of DF
. So I should not use sapply
. In this case, let's do a full vectorization:
MAT <- t(DF)
result <- colSums(MAT == 1 & rbind(diff(MAT) == 0, FALSE)) > 0
table(result)
#FALSE TRUE
# 377 3719
In this case colSums
can not be changed to any
. The vectorization comes at more memory usage, but is probably worthwhile.