开发者

Get the index of the values of one vector in another?

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开发者_StackOverflow 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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜