2016-03-29 38 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 
相關問題