我想要一个函数来返回向量匹配子序列的初始索引。例如:
y <- c("a","a","a","b","c")
multi_match(c("a","a"), y)
# [1] 1 2
multi_match(c("a","b"), y)
# [1] 3
我有一个粗略的实现,但我觉得我必须重新发明轮子,而且有点笨拙。有没有更好的方法来实现这一点,或者在某个地方是否存在具有类似功能的预先存在的功能?
multi_match <- function(x, table){
# returns initial indicies of all substrings in table which match x
if(length(table) < length(x)){
return(NA)
}else{
check_mat <- matrix(nrow = length(x), ncol = length(table))
for(i in 1:length(x)){
check_mat[i,] <- table %in% x[i]
}
out <- vector(length = length(table))
for(i in 1:(length(table)-(length(x)-1))){
check <- vector(length=length(x))
for(j in 1:length(x)){
check[j] <- check_mat[j,(i+(j-1))]
}
out[i] <- all(check)
}
if(length(which(out))==0){
return(NA)
}else{
return(which(out))
}
}
}