Get Row Index Number in R (Example) | Find Indices in Data Frame

 

In this tutorial you’ll learn how to return the referencing row index number in the R programming language.

The post consists of these content blocks:

So let’s jump right to the tutorial.

 

Creation of Example Data

First, we’ll need to construct some data that we can use in the examples below:

data <- data.frame(x1 = 1:10,              # Create example data frame
                   x2 = 10:1,
                   x3 = 7)
rownames(data) <- letters[1:nrow(data)]    # Modify row names of data
data                                       # Print example data frame
#   x1 x2 x3
# a  1 10  7
# b  2  9  7
# c  3  8  7
# d  4  7  7
# e  5  6  7
# f  6  5  7
# g  7  4  7
# h  8  3  7
# i  9  2  7
# j 10  1  7

As you can see based on the previous output of the RStudio console, our example data contains ten rows and three columns. The row names of our data frame are alphabetical letters.

 

Example: Returning Row Index Number Using which() & rownames() Functions

This Example shows how to return the index number of a data frame row corresponding to a certain row name (i.e. “f”). For this, we can use the which and rownames functions as shown below:

which(rownames(data) == "f")               # Applying which & rownames
# 6

The RStudio console returns the value 6, i.e. the sixth row of our data frame has the row name “f”.

We can double check this by creating a subset of our data frame that contains only the sixth row:

data[6, ]                                  # Subsetting data frame
#   x1 x2 x3
# f  6  5  7

As you can see based on the previous output, we extracted only the “f”-row from our data. Looks good!

 

Video, Further Resources & Summary

Would you like to know more about row indices? Then you might watch the following video which I have published on my YouTube channel. In the video, I’m explaining the content of this article:

 

 

Furthermore, I can recommend to read the other articles of my website.

 

You learned in this article how to identify the row index number in a data frame in the R programming language. Let me know in the comments section, if you have any additional questions. Besides that, don’t forget to subscribe to my email newsletter to get updates on new tutorials.

 

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