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.
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.
Returns an INTEGER value that indicates the position of the target string within the source string.
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.
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 == ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With