Эта функция должна работать:
my_function <- function(x, find) {
# we create two matrix from rle function
m = matrix(unlist(rle(x)), nrow=2, byrow = T)
n = matrix(unlist(rle(find)), nrow=2, byrow = T)
# for each column in m we see if its equal to n
temp_bool = apply(m, 2, function(x) x == n) # this gives a matrix of T/F
# then we simply sum by columns, if we have at least a 2 it means that we found (1,1) at least once
temp_bool = apply(temp_bool, 2, sum)
# updated part
if (any(temp_bool==2)) {
return(position = which(temp_bool==2)+1)
} else {
return(position = FALSE)
}
}
my_function(x, find)
#[1] 4
my_function(y, find)
#[1] FALSE
Чтобы было понятнее, я покажу результаты этих двух apply
:
apply(m, 2, function(x) x == n)
# [,1] [,2] [,3] [,4] [,5]
# [1,] FALSE TRUE TRUE FALSE FALSE
# [2,] TRUE FALSE TRUE FALSE TRUE # TRUE-TRUE on column 3 is what we seek
apply(temp_bool, 2, sum)
#[1] 1 1 2 0 1
Пример данных:
x <- c(1,0,0,1,1,0,1)
y <- c(1,0,1,1,1,0)
find <- c(1,1) # as pointed this needs to be a pair of the same number