Convert Values in Column into Row Names of Data Frame in R (Example)

 

In this post you’ll learn how to use variable values as row names in R programming.

Table of contents:

With that, let’s start right away.

 

Creating Example Data

Let’s create an example data frame in R:

data <- data.frame(x1 = LETTERS[1:5],           # Create example data
                   x2 = 5:9)
data                                            # Print example data
#   x1 x2
# 1  A  5
# 2  B  6
# 3  C  7
# 4  D  8
# 5  E  9

As you can see based on the output of the RStudio console, our example data contains five rows and two columns.

 

Example 1: Use Variable Values as Row Names in R

If we want to use the values stored in one of our variables as row names of our data frame (or a matrix), we can use the row.names function in R:

row.names(data) <- data$x1                      # Convert column to row names
data                                            # Print updated data
#   x1 x2
# A  A  5
# B  B  6
# C  C  7
# D  D  8
# E  E  9

Have a look at the previously shown output of the RStudio console. As you can see, the row names were changed from the default numeric range to the values of our column x1.

 

Video & Further Resources

Do you need more information on the content of this tutorial? Then I can recommend to have a look at the following video of my YouTube channel. I’m explaining the content of this article in the video.

 

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.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Also, you might have a look at some of the related articles on https://www.statisticsglobe.com/. Please find a selection of tutorials about the manipulation of data frames, matrices, data tables, and tibbles below.

 

This tutorial illustrated how to define row names based on the elements of a variable in R. Let me know in the comments, if you have further questions.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top