35

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.

1

3 Answers 3

52

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
Sign up to request clarification or add additional context in comments.

2 Comments

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!
w00te: in the R sources, [R]\src\library\base\R\match.R and [R]\src\main\match.c
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.