How to Retrieve Row Numbers in R DataFrame?
Last Updated :
19 Dec, 2021
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
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" )
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
data_frame <- data.frame (col1 = letters [1:10],
col2 = 2:11,
col3 = TRUE )
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" )
which ( rownames (data_frame)== "E" )
|
Output
Share your thoughts in the comments
Please Login to comment...