34

I would guess this is a duplicate, but I can't find that so here goes...

I'd like to return the index of second in first:

first = c( "a" , "c" , "b" )
second = c( "c" , "b" , "a" )
result = c( 2 , 3 , 1 )

I guarantee that first and second have unique values, and the same values between the two.

Suraj
  • 35,905
  • 47
  • 139
  • 250
  • Possible duplicate of [Is there an R function for finding the index of an element in a vector?](https://stackoverflow.com/questions/5577727/is-there-an-r-function-for-finding-the-index-of-an-element-in-a-vector) – divibisan Apr 16 '19 at 00:34

3 Answers3

49

Getting indexes of values is what match() is for.

 first = c( "a" , "c" , "b" )
 second = c( "c" , "b" , "a" )
 match(second, first)
 [1] 2 3 1
mdsumner
  • 29,099
  • 6
  • 83
  • 91
  • mdsummer - thanks! the second part wasn't a questions, I was just stating some bounds to the problem (edited to make that more clear). your solution works great! – Suraj Sep 23 '11 at 14:51
  • w00te: in the R sources, [R]\src\library\base\R\match.R and [R]\src\main\match.c – mdsumner Sep 23 '11 at 14:51
  • clear question, clear answer! That's very nice and very rare example!!! :-) +1 +1 – Tomas Sep 23 '11 at 19:08
4

I was solving related problem, selecting the elements of a vector based on a pattern. Lets say we have vector 'a' and we would like to find the occurrences of vector 'b'. Can be used in filtering data tables by a multiply search patterns.

a=c(1, 1, 27, 9, 0, 9, 6, 5, 7)
b=c(1, 9)

match(a, b)
[1] 1  1 NA  2 NA  2 NA NA NA

So match() it is not really useful here. Applying binary operator %in% is more convenient:

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

a[a %in% b]
[1] 1 1 9 9

Actually from the match() help %in% is just a wrap around match() function:

"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0
makaveli_lcf
  • 113
  • 1
  • 5
0

here is another not efficient solution with which and sapply:

sapply(second, function(x) which(first==x)[1])

for every element of the second returns the first index found in first. if no match found NA is returned for that element

asalimih
  • 298
  • 2
  • 8