I'd like to have a function which returns the initial indicies of matching subsequences of a vector. For example:
y <- c("a","a","a","b","c")
multi_match(c("a","a"), y)
# [1] 1 2
multi_match(c("a","b"), y)
# [1] 3
I have a rough implementation, but I feel like I must be reinventing the wheel, and it's a little clunky. Is there a better way to implement this, or is there a pre-existing function somewhere with similar functionality?
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))
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…