Here is another solution.
I must admit that the function is not mine, I saw it somewhere a long time ago and have not written in the .R file where I found it, so I cannot give the credits.
But it does what is asked for, to find a given sub-sequence of a vector. The data is recreated because in the question the data.frame has two test2 and because sample is a base function. I have changed both.
occurs <- function(x, y) {
m <- length(x)
n <- length(y)
candidate <- seq.int(length = n - m + 1L)
for (i in seq.int(length = m)) {
candidate <- candidate[x[i] == y[candidate + i - 1L]]
}
candidate
}
x <- rep(TRUE, 3)
df1 <- data.frame(test1 = rep(c(TRUE, FALSE, TRUE, TRUE), 3),
test2 = rep(c(TRUE, FALSE, FALSE, TRUE), 3),
test3 = rep(c(TRUE, FALSE, FALSE, FALSE), 3))
occurs(x, df1$test1)
#[1] 3 7
lapply(df1, \(y) occurs(x, y))
#$test1
#[1] 3 7
#
#$test2
#integer(0)
#
#$test3
#integer(0)
The sequence is present twice in test1 at positions 3 and 7 and not present in the other columns.
Edit
A run of occurs with only the first df1 column, renamed y.
The algorithm is to have a moving window into y, and to match it to the sequence in x.
The reassignment of candidate each iteration through the loop will keep shortening the candidate vector. In the end only the sequence of elements of y that match all elements of x will still be in candidate.
x <- rep(TRUE, 3)
y <- rep(c(TRUE, FALSE, TRUE, TRUE), 3)
m <- length(x)
n <- length(y)
(candidate <- seq.int(length = n - m + 1L))
# [1] 1 2 3 4 5 6 7 8 9 10
i <- 1L
which(x[i] == y[candidate + i - 1L])
which(x[1] == y[c(1,2,3,4,5,6,7,8,9,10)]
which(TRUE == c(TRUE,FALSE,TRUE,TRUE,TRUE,FALSE,TRUE,TRUE,TRUE,FALSE))
#[1] 1 3 4 5 7 8 9
# remove 2nd, 6th and 10th from candidate
(candidate <- candidate[x[i] == y[candidate + i - 1L]])
#[1] 1 3 4 5 7 8 9
i <- 2L
which(x[i] == y[candidate + i - 1L])
which(x[2] == y[c(2,4,5,6,8,9,10)]
which(TRUE == c(FALSE,TRUE,TRUE,FALSE,TRUE,TRUE,FALSE))
#[1] 2 3 5 6
# shorten to 2nd, 3rd, 5th and 6th of candidate
(candidate <- candidate[x[i] == y[candidate + i - 1L]])
#[1] 3 4 7 8
i <- 3L
which(x[i] == y[candidate + i - 1L])
which(x[3] == y[c(5,6,9,10)]
which(TRUE == c(TRUE,FALSE,TRUE,FALSE))
#[1] 1 3
# shorten to 1st and 3rd of candidate
(candidate <- candidate[x[i] == y[candidate + i - 1L]])
#[1] 3 7