All the data frames have row names. Using the row.names() or row.names.data.frame() function in R, we can get the data frame row names.
row.names() or row.names.data.frame() function gets the character vectors of the length of the rows in the data frame.
In this tutorial, we will discuss about how to get data frame row names in R using row.names() and row.names.data.frame() function.
Get R Data Frame Row Names using row.names
Use the row.names() function which takes data frame object and returns the data frame row names as character vectors.
Let’s practice getting data frame row names using the example.
Create a data frame in R using data.frame() function.
# Create a data frame
student_info <- data.frame(
name = c("Tom","Kim","Sam","Julie","Emily","Chris"),
age = c(20,21,19,20,21,22),
gender = c('M','F','M','F','F','M'),
marks = c(72,77,65,80,85,87)
)
# Print data frame
student_info
In the above R code, it creates a data frame and the row length is 6, the output of the above data frame object is:
name age gender marks
1 Tom 20 M 72
2 Kim 21 F 77
3 Sam 19 M 65
4 Julie 20 F 80
5 Emily 21 F 85
6 Chris 22 M 87
The first column represents the data frame row names.
Get the row names of a data frame using row.names() function in R.
# Gets the data frame row names
row.names(student_info)
Run the above R code to get data frame row names. It returns the character vectors of the length of the row.
[1] "1" "2" "3" "4" "5" "6"
Get Row Names of Data Frame using row.names.data.frame()
Using the row.names.data.frame(x) function in R, we can get the data frame row names.
Let’s consider an example to illustrate how to get row names of a data frame in R.
Create a data frame.
# Create a data frame
sales_data <- data.frame(
id = c(1,2,3,4,5,6),
name = c("Ebook","Audio","Video","Course","Book","Software"),
revenue = c(45500,53000,55200,13650,33400,13800)
)
# Sets the custom row name for data frame
row.names(sales_data) <- letters[1:6]
# Print the data frame
sales_data
Run the above R code to create a data frame and print it. In this example, for illustration, we have set the custom names for rows using the row.names() function.
The output of the above R code is:
id name revenue
a 1 Ebook 45500
b 2 Audio 53000
c 3 Video 55200
d 4 Course 13650
e 5 Book 33400
f 6 Software 13800
Get the data frame row names using the row.names.data.frame() function in R.
# Gets the row names for data frame
row.names.data.frame(sales_data)
[1] "a" "b" "c" "d" "e" "f"
Conclusion
I hope the above article to get data frame row names are helpful to you.
Using the row.names() and row.names.data.frame() function in R, we can extract row names from the data frame.