Substitute Data Frame Row Names by Values in Vector in R (2 Examples)
On this page you’ll learn how to replace the row names of a data frame by the values in a vector in the R programming language.
The article consists of the following information:
Let’s dive right into the examples…
Creation of Example Data
First, we’ll need to construct some example data:
data <- data.frame(x1 = 1:5, # Creating data frame x2 = letters[3:7], x3 = "abc") data # Printing data frame # x1 x2 x3 # 1 1 c abc # 2 2 d abc # 3 3 e abc # 4 4 f abc # 5 5 g abc
The previously shown output of the RStudio console shows the structure of our example data – It shows that the row names of our example data frame are ranging from 1 to 5.
Let’s substitute those row names!
Example 1: Replace Row Names by Values in Vector
In this example, I’ll show how to rename the rows of a data frame based on a vector of names. First, we have to create such a vector in R:
new_names <- 11:15 # Vector with new row names new_names # Printing new names # 11 12 13 14 15
As you can see, our vector consists of numeric values ranging from 11 to 15.
Now, we can use the rownames function to adjust our row names:
rownames(data) <- new_names # Applying rownames function data # Printing updated data # x1 x2 x3 # 11 1 c abc # 12 2 d abc # 13 3 e abc # 14 4 f abc # 15 5 g abc
Have a look at the previous output of the RStudio console: It shows that the row names of our data frame were substituted by the values in our vector.
Example 2: Replace Row Names by Values in Data Frame Column
It is also possible to convert the values in a variable of our data frame to the row names.
Have a look at the following R code:
rownames(data) <- data$x2 # Applying rownames function data # Printing updated data # x1 x2 x3 # c 1 c abc # d 2 d abc # e 3 e abc # f 4 f abc # g 5 g abc
As you can see, the row names are equal to the values in the column x2. Also note that this time we have used characters instead of numeric values.
Video, Further Resources & Summary
Do you need more info on the R codes of the present tutorial? Then I can recommend to have a look at the following video tutorial of my YouTube channel. I show the R programming code of this post in the video tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Also, you could have a look at the related articles of this website.
- Don’t Display Data Frame Row Names
- Convert Row Names into Column of Data Frame in R
- Merge Data Frames by Row Names in R
- Convert Values in Column into Row Names of Data Frame
- Change Row Names of Data Frame or Matrix in R
- All R Programming Tutorials
You learned in this tutorial how to exchange data frame row names in R. In case you have any further comments and/or questions, don’t hesitate to let me know in the comments below.
Statistics Globe Newsletter