Find Index of Element in Vector in R (2 Examples)

 

In this article, I’ll show how to find the index of an element in a vector in the R programming language.

The tutorial will contain this content:

Let’s dive into it!

 

Example Data

In the examples of this tutorial, I’ll use the following example vector:

x <- c(4, 1, 6, 7, 2, 1, 1)   # Create example vector

As you can see based on the previous R code, our example vector simply contains seven numeric values.

 

Example 1: Find Index of First Match in Vector (match Function)

Let’s assume that we want to know the index of the first element of our vector, which is equal to the value 1. Then we can apply the match R function as follows:

match(1, x)                   # match function finds first element
# 2

Within the function, we had to specify the value we are searching for (i.e. 1) and the vector within which we want to search (i.e. our example vector with the name x).

The RStudio console output shows us the position of the first element of our vector, which is equal to 1. In our example, this is the second element.

 

Example 2: Identify All Matching Elements in Vector (%in% Operator)

In Example 1, we identified only the first element of our example vector, which is equal to 1.

However, we might want to know all indices of the value 1 within our vector. In this case, we can apply the %in% operator in combination with the which command as follows:

which(x %in% 1)               # which function identifies all elements
# 2 6 7

As you can see based on the RStudio console output, our example vector contains the value 1 at positions 2, 7, and 7.

 

Video, Further Resources & Summary

Do you need more information on the R syntax of this article? Then I can recommend to have a look at the following video of my YouTube channel. I’m explaining the R programming code of this tutorial in the video:

 

 

Furthermore, you might have a look at the other articles of this homepage. Please find some posts below:

 

In this tutorial, I showed how to get the index of certain elements in a vector in the R programming language. In case you have further questions, don’t hesitate to tell me about it in the comments.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top