Get Row Indices where Data Frame Column has a Particular Value in R (2 Examples)

 

In this article you’ll learn how to return the row indices of rows with a specific column value in the R programming language.

Table of contents:

Let’s dig in…

 

Creation of Example Data

First, we’ll need to create some data that we can use in the examples later on:

data <- data.frame(x1 = 15:10,    # Creating example data
                   x2 = c(7, 3, 5, 7, 7, 1),
                   x3 = letters[7:2])
data                              # Printing example data
#   x1 x2 x3
# 1 15  7  g
# 2 14  3  f
# 3 13  5  e
# 4 12  7  d
# 5 11  7  c
# 6 10  1  b

The previous output of the RStudio console shows that our example data has six rows and three columns.

 

Example 1: Row Indices where Data Frame Column has Particular Value

The following syntax illustrates how to extract the row numbers of a data frame where a variable contains a specific value.

More precisely, this example shows the row indices of our data where the variable x2 is equal to the value 7. For this, we are using the which function in R:

which(data$x2 == 7)               # Applying which function
# 1 4 5

The RStudio console returns a vector containing the values 1, 4, and 5. In other words: the first, fourth, and fifth rows of our data frame contain the value 7 in the column x2.

 

Example 2: Subsetting Data Frame According to Particular Value in Column

The following R code shows how to create a data frame subset based on the logical condition that we have specified within the which() function (see Example 1).

Have a look at the following R code:

data[which(data$x2 == 7), ]       # Conditionally subsetting data
#   x1 x2 x3
# 1 15  7  g
# 4 12  7  d
# 5 11  7  c

As you can see, we have created a new data frame that consists only of those rows where the variable x2 is equal to the value 7.

 

Video & Further Resources

Do you need more information on the content of this tutorial? Then you may want to watch the following video tutorial of my YouTube channel. In the video, I illustrate the R programming syntax of this article.

 

 

Besides the video, you might have a look at the other tutorials on my website.

 

In summary: In this post you learned how to get the rows of a data frame where a variable has a particular value in R. Don’t hesitate to let me know in the comments below, if you have any further questions. Furthermore, please subscribe to my email newsletter in order to get updates on the newest articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top