1

I have two vectors, let's say

a <-  c('Q1', 'Q2', 'Q3')

and

b <- c('Q10', 'Q13', 'Q1', 'Q1', 'Q40', 'Q2', 'Q2', 'Q2')

Now I want to find the indices of the elements in a in b. So the result should be [3, 4, 6, 7, 8]. I tried to to it with match(a, b), but this results in only the first occurrence of a in b so [3, 6].

Does anyone know how to do this in R?

Mr.Rlover
  • 2,523
  • 3
  • 14
  • 32
bml
  • 115
  • 7

1 Answers1

3
a <-  c('Q1', 'Q2', 'Q3')
b <- c('Q10', 'Q13', 'Q1', 'Q1', 'Q40', 'Q2', 'Q2', 'Q2')

which(b %in% a)

[1] 3 4 6 7 8
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Mr.Rlover
  • 2,523
  • 3
  • 14
  • 32
  • 2
    Just to add to your answer for OP. ``match()`` was not working because ``match()`` returns a vector of the positions of (first) matches of its first argument in its second as read in the R Documentation. – Gainz Mar 05 '20 at 16:16