Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 268
SFun28 Avatar asked Sep 23 '11 14:09

SFun28


People also ask

What is the index of a vector?

Vector Indexing, or vector index notation, specifies elements within a vector. Indexing is useful when a MATLAB program only needs one element of a series of values. Indexing is often used in combination with repetition structures to conduct the same process for every element in an array.

What is index function R?

Returns an INTEGER value that indicates the position of the target string within the source string.

Is vector index based?

Vectors are dynamic in nature which can be resized on the insertion and deletion of elements. As it is not index-based, accessing elements is done through the use of iterators and is more time-consuming.

How do you get the index of a value in a vector in R?

Use the which() Function to Find the Index of an Element in R. The which() function returns a vector with the index (or indexes) of the element which matches the logical vector (in this case == ).


2 Answers

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 
like image 187
mdsumner Avatar answered Oct 12 '22 15:10

mdsumner


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 
like image 37
makaveli_lcf Avatar answered Oct 12 '22 15:10

makaveli_lcf