How to Exchange Row Names of Data Frame in R (Example Code)
In this tutorial, I’ll show how to modify the row names of a data frame in the R programming language.
Creating Example Data
data(iris) # Loading iris data set head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading iris data set head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
iris_names <- paste0("row_", 1:nrow(iris)) # Specify vector of new row names iris_names # Show new row names in RStudio console # "row_1" "row_2" "row_3" "row_4" "row_5" "row_6" ... |
iris_names <- paste0("row_", 1:nrow(iris)) # Specify vector of new row names iris_names # Show new row names in RStudio console # "row_1" "row_2" "row_3" "row_4" "row_5" "row_6" ...
Example: Exchanging Row Names of Data Frame by Values in Vector
rownames(iris) <- iris_names # Using rownames() function head(iris) # Show head of updated iris data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # row_1 5.1 3.5 1.4 0.2 setosa # row_2 4.9 3.0 1.4 0.2 setosa # row_3 4.7 3.2 1.3 0.2 setosa # row_4 4.6 3.1 1.5 0.2 setosa # row_5 5.0 3.6 1.4 0.2 setosa # row_6 5.4 3.9 1.7 0.4 setosa |
rownames(iris) <- iris_names # Using rownames() function head(iris) # Show head of updated iris data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # row_1 5.1 3.5 1.4 0.2 setosa # row_2 4.9 3.0 1.4 0.2 setosa # row_3 4.7 3.2 1.3 0.2 setosa # row_4 4.6 3.1 1.5 0.2 setosa # row_5 5.0 3.6 1.4 0.2 setosa # row_6 5.4 3.9 1.7 0.4 setosa
Related Tutorials
Have a look at the following R programming language tutorials. They illustrate topics such as extracting data, groups, and naming data: