Find Row Number in R

The which()
method is used to find the row number for a value of a data frame in R. This tutorial demonstrates how to use the which()
method to find a row number in R.
Find Row Number in R
The which()
method retrieves a row number for a value in R and returns the row number. If it finds otherwise, it returns the integer 0
.
Syntax:
which (dataframe$coloumnname == value)
This method takes the value as a given parameter as referenced with the $
symbol between the data frame and column name. The which()
method is used to retrieve the row number, which corresponds to the true
condition of the specific expression in the data frame.
Code Example:
#create a dataframe
Delftstack <- data.frame(Name=c('Jack', 'John', 'Mike', 'Michelle', 'Jhonny'),
LastName=c('Danials', 'Cena', 'Chandler', 'McCool', 'Nitro'),
Id=c(101, 102, 103, 104, 105),
Designation=c('CEO', 'Project Manager', 'Senior Dev', 'Junior Dev', 'Intern'))
print ("The Original DataFrame:")
print(Delftstack)
print("DataFrame Row Number Where Designation value is Senior Dev: ")
# get the row number
which(Delftstack$Designation == "Senior Dev")
The code above will find the row number for the value Senior Dev
from the Designation column of the data frame.
Output:
[1] "The Original DataFrame:"
Name LastName Id Designation
1 Jack Danials 101 CEO
2 John Cena 102 Project Manager
3 Mike Chandler 103 Senior Dev
4 Michelle McCool 104 Junior Dev
5 Jhonny Nitro 105 Intern
[1] "DataFrame Row Number Where Designation value is Senior Dev"
[1] 3
We can also assign names to the rows using the rownames()
method. This method takes a vector equal to the number of rows in the data frame.
We can pass this method to the which method to find the row number for a particular value.
Code Example:
# create a dataframe
DelftstackNew <- data.frame(Column1 = 1:20,
Column2 = 20:1,
Column3 = 9)
# Get the rows of dataframe
numberofrows <- nrow(DelftstackNew)
rownames(DelftstackNew) <- LETTERS[1:numberofrows]
print ("The Original DataFrame: ")
print(DelftstackNew)
print("DataFrame Row Number Where value is S:")
# get R value in column
which(rownames(DelftstackNew)=="S")
The code above will find the row number for the value S
.
Output:
[1] "The Original DataFrame: "
Column1 Column2 Column3
A 1 20 9
B 2 19 9
C 3 18 9
D 4 17 9
E 5 16 9
F 6 15 9
G 7 14 9
H 8 13 9
I 9 12 9
J 10 11 9
K 11 10 9
L 12 9 9
M 13 8 9
N 14 7 9
O 15 6 9
P 16 5 9
Q 17 4 9
R 18 3 9
S 19 2 9
T 20 1 9
>
[1] "DataFrame Row Number Where value is S:"
[1] 19
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook