2016-03-29 39 views
2

我想知道如何匹配整个矢量。我有两个向量a,b如何匹配矢量元素作为一个整体

a <- c(5,1,2,6,3,4,8) 
b <- c(1,2,3) 

我知道一些方法来匹配矢量元素,如

match(b,a) 
#[1] 2 3 5 

b%in%a 
#[1] TRUE TRUE TRUE 

match()我得到各个矢量元素的位置和%in%我得到合乎逻辑的各个矢量元素。但我期待一次匹配整个向量ba。它不应该匹配单个元素,而是整个矢量,并获取匹配开始的位置。

所需的输出:

在上述载体没有找到匹配的,因为我找的全矢量不是个别的载体项目。

+0

@Henrik 。感谢您找到可能的重复。我看看,可能会有所帮助。 –

+0

@rawr感谢您指导链接。问题已经关闭,提供的链接似乎没有关系。 'Henrik'早些时候提供的链接后来被删除,效果很好。谢谢大家! –

+0

@rawr !!。我指的是顶部的链接而不是链接。请不要删除链接。 –

回答

0

你总是可以蛮力这个,只是通过元素向量元素循环。

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 

同样,你会得到通过编译功能显着的速度收益。

0

的一种方法,有几个例子:

wholematch<-function(a=c(5,1,3,2,1,2,5,6,2,6),b=c(1,2,6)) 
{ 
    for(loop.a in 1:(length(a)-length(b))) 
    { 
    #pmatch gives the first occurrence of each value of b in a. To be sure of finding the consecutive matches, use pmatch starting from all the possible positions of "a" 
    wmatch<-(loop.a-1)+pmatch(b,a[loop.a:length(a)]) 
    #If at any time the number of matches is less than the length of the vector to match, we will never find a match. Return NA 
    if(length(na.omit(pmatch(b,a[loop.a:length(a)])))<length(b)) return(NA) 
    #If all indices are adjacent, return the vector of indices 
    if(max(diff(wmatch))==1) return(wmatch) #return(wmatch[1]) if you only want the start 
    } 
} 

wholematch() 
[1] NA 

wholematch(a=c(5,1,3,2,1,2,5,6,2,6),b=c(6,2,6)) 
[1] 8 9 10 
1

怎么样,如果我们检查的长度(以na.omit)的match()输出针对载体的,我们正在测试

ifelse(length(na.omit(match(b, a))) == length(b), match(b, a)[1], NA) 
#[1] 2 
#adding a new value in b so it wont match, we get 
b <- c(1, 2, 3, 9) 
ifelse(length(na.omit(match(b, a))) == length(b), match(b, a)[1], NA) 
#[1] NA 
相关问题