你总是可以蛮力这个,只是通过元素向量元素循环。
a <- c(5,1,2,6,3,4,8)
b <- c(1,2,3)
matchr <- function(a,b){
# First, loop through the a vector
for(i in 1:(length(a)-length(b))){
pos <- FALSE
# Next loop through the b vector,
for(j in 1:length(b)){
# as we're looping through b, check if each element matches the corresponding part of the a vector we're currently at.
if(a[i+j-1] == b[j]){
pos <- TRUE
} else{
pos <- FALSE
break
}
}
# if all the elements match, return where we are in the a vector
if(pos == TRUE){
return(i)
}
}
# if we finish the a vector and never got a match, return no match.
return("No match")
}
matchr(a,b)
[1] "No match"
d <- c(7,5,4,2,1,2,3,8,5)
matchr(d,b)
[1] 5
e <- c(2,3,8)
matchr(d,e)
[1] 6
如果你真正的载体是更大的,你可以考虑通过matchr <- compiler::cmpfun(matchr)
编译该函数或重写RCPP它。
编辑:另一种方法
让你a
矢量份额为length(b)
大小的矢量的列表,然后测试是否list(b)
是在分割了a
列表:
matchr2 <- function(a){
m <- list()
for(i in 1:(length(a)-length(b))){
m[[i]] <- c(a[i : (length(b) + i - 1)])
}
m
}
mlist <- matchr2(a)
list(b) %in% mlist
[1] FALSE
mlist <- matchr2(d)
list(b) %in% mlist
[1] TRUE
同样,你会得到通过编译功能显着的速度收益。
@Henrik 。感谢您找到可能的重复。我看看,可能会有所帮助。 –
@rawr感谢您指导链接。问题已经关闭,提供的链接似乎没有关系。 'Henrik'早些时候提供的链接后来被删除,效果很好。谢谢大家! –
@rawr !!。我指的是顶部的链接而不是链接。请不要删除链接。 –