代码之家  ›  专栏  ›  技术社区  ›  Andre Elrico

匹配序列。获取遵循模式的元素的索引

  •  2
  • Andre Elrico  · 技术社区  · 6 年前
    set.seed(3)
    
    pattern <- letters[1:4]
    #[1] "a" "b" "c" "d"
    vec<-sample(letters[1:4],25,replace=T)
    names(vec) <- seq_along(vec)
    

    数据:

    # 1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26 
    #"a" "d" "b" "b" "c" "c" "a" "b" "c" "c" "c" "c" "c" "c" "d" "d" "a" "c" "d" "b" "a" "a" "a" "a" "a" "d" 
    

    预期结果:

    c(1,3,5,15,17,20) #<< This is the desired result I want to find
    
    # 1   3   5  15  17  20   #<< (This is for explanation purpose)
    #"a" "b" "c" "d" "a" "b"
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Hobo Sheep    6 年前

    here

    pattern <- letters[1:4]
    keep <- logical(length(vec))
    
    s <- 0
    for (i in seq_along(keep)){
        if (pattern[s +1] == vec[i]){
            keep[i] <- T
            s <- (s + 1) %% length(pattern)
        } else {
            keep[i] <- F
        }
    }
    
    
    vec_filtered <- vec[keep]
    

    which(keep)
    
        2
  •  1
  •   Ronak Shah    6 年前

    #Initialise index to loop through "pattern" and "vec"
    i = 1
    j = 1
    #Create a new variable to store index values
    index = numeric()
    #Until "vec" is not over
    while (i < length(vec)) {
       #Check if a match is found
       if(vec[i] == pattern[j]) {
         #If found store the index
         index = c(index, i)
         j = j + 1
         #Recycle the "pattern" object and continue searching till "vec" is not over
         if (j > length(pattern))
           j = 1
        }
       i = i + 1
    }
    
    index
    #[1]  1  3  5 15 17 20