56
You can use the row.names() function to quickly get and set the row names of a data frame in R.
This tutorial provides several examples of how to use this function in practice on the built-in mtcars dataset in R:
#view first six rows of mtcars
head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
How to Get Row Names
You can use the following syntax to view the first few row names of the mtcars data frame:
#view first six row names of mtcars head(row.names(mtcars)) [1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" [4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant"
How to Change One Row Name
You can use the following syntax to change on specific row name:
#change the row name called Datsun710 to 710 row.names(mtcars)[row.names(mtcars) == "Datsun 710"] 710" #view first six row names of mtcars head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
How to Change All Row Names
You can use the following syntax to change all of the row names to a list of integers starting at 1:
#change row names to a list of integers row.names(mtcars) nrow(mtcars) #view first six row names of mtcars head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
You can also use the paste() function to append a word in front of each row name:
#change row names row.names(mtcars) row", 1:nrow(mtcars)) #view first six row names of mtcars head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb row 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 row 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 row 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 row 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 row 5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 row 6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Note that each row now has the word “row” appended to the front.
Additional Resources
How to Retrieve Row Numbers in R
How to Append Rows to a Data Frame in R
How to Select Random Samples in R