2
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)

Data:

# 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" 

Desired Outcome:

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"
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69

2 Answers2

2

A similar question has been addressed recently 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]

As you have modified your question, here is what you want:

which(keep)
Hobo Sheep
  • 389
  • 2
  • 11
1

Another way using traditional programming approach

#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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213