which()Function to Find the Index of an Element in R
match()Function to Find the Index of an Element in R
A vector is one of the fundamental data structures in R. It is used to store elements in a sequence, but unlike lists, all elements in a vector must be of the same data type.
Every element in the vector has a particular position or index. It is possible to know the index of any element using built-in functions in R like
In this tutorial, we will find the index of element
8 of the following vector:
x <- c(5,6,8,9,7,5,7,8)
which() Function to Find the Index of an Element in R
which() function returns a vector with the index (or indexes) of the element which matches the logical vector (in this case
x <- c(5,6,8,9,7,5,7,8) which(x == 7)  5 7
Notice that since
7 is present twice in the vector, both of its positions are returned. If we want the first index of
7, we can simply do it as shown below:
which(x == 7)  5
We can also use the
which() function to find the indexes of multiple elements using the
%in% parameter, which returns a vector with a
TRUE value for every element that matches.
which(x %in% c(7,8))  3 5 7 8
As you can see, all the positions of both
8 are returned.
match() Function to Find the Index of an Element in R
match() function is very similar to the
which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the
x <- c(5,6,8,9,7,5,7,8) match(7,x)  5
We can also use it for finding the first index of multiple elements, as shown below:
x <- c(5,6,8,9,7,5,7,8) match(c(7,8),x)  5 3
Note that only the first positions of both
8 are returned by the
match() function. That is why the
match() is considered to be faster of the two methods for such situations where only the first index is required.