Open In App
Related Articles

How to Retrieve Row Numbers in R DataFrame?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will discuss how to Retrieve Row Numbers in R Programming Language.

The dataframe column can be referenced using the $ symbol, which finds its usage as data-frame$col-name. The which() method is then used to retrieve the row number corresponding to the true condition of the specified expression in the dataframe. The column values are matched and then the row number is returned. In case, the condition doesn’t correspond to any row number, then integer(0) is returned. 

Syntax:

which (df$col-name == val)

Example:

R

#creating a dataframe
data_frame <- data.frame(col1 = letters[1:10],              
                   col2 = 2:11,
                   col3 = TRUE)
print ("Original DataFrame")
  
print(data_frame)
  
print("DataFrame Row Number Where Column1 value is b")
  
# get column value b in col1 column
which(data_frame$col1 == "b")

                    

Output

Rownames can also be assigned to the rows in a dataframe using the rownames() method. It takes a vector of length equivalent to the number of rows in the dataframe. The rownames(df) can also be checked to compare a value and then return a row number which corresponds to it.

Example 2:

R

# creating a dataframe
data_frame <- data.frame(col1 = letters[1:10],              
                   col2 = 2:11,
                   col3 = TRUE)
# GETTING THE ROWS OF dataframe
rows <- nrow(data_frame)
  
rownames(data_frame) <- LETTERS[1:rows] 
print ("Original DataFrame")
  
print(data_frame)
  
print("DataFrame Row Number Where Row Name value is E")
  
# get R value in column
which(rownames(data_frame)=="E")

                    

Output



Last Updated : 19 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads