How to Modify Row Names of Matrix & Data Frame in R (Example Code)

In this post, I’ll show how to adjust row names of data frames and matrices in the R programming language.

Creating Example Data

my_df <- data.frame(col1 = 10:15,    # Constructing example data frame
                    col2 = 6,
                    col3 = LETTERS[9:4],
                    col4 = c(7, 4, 2, 1, 7, 6))
my_df                                # Returning example data frame to console
#   col1 col2 col3 col4
# 1   10    6    I    7
# 2   11    6    H    4
# 3   12    6    G    2
# 4   13    6    F    1
# 5   14    6    E    7
# 6   15    6    D    6

Example: Changing Row Names of Data Frame Using row.names() Function

row.names(my_df) <- 101:106          # Adjusting row names
my_df                                # Returning new data frame to RStudio console
#     col1 col2 col3 col4
# 101   10    6    I    7
# 102   11    6    H    4
# 103   12    6    G    2
# 104   13    6    F    1
# 105   14    6    E    7
# 106   15    6    D    6

Related Tutorials

You may find some additional R tutorials on topics such as vectors and naming data below.

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.
You need to agree with the terms to proceed

Menu
Top