R Modify Row & Column Names of Data without Dimensions (Example Code)

This tutorial shows how to set row and column names without knowing the number of rows and columns in R.

Example Data

data(iris)                                                    # Example 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

Example: Change Row & Column Names of Data Frame Using dimnames() Function

iris_new <- iris                                              # Duplicate iris data
dimnames(iris_new) <- list(paste0("row_", 1:nrow(iris_new)),  # Change row & colnames
                           paste0("X", 1:ncol(iris_new)))
head(iris_new)                                                # Show updated data in RStudio
#        X1  X2  X3  X4     X5
# 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 & Further Resources

Have a look at the following R tutorials. They illustrate topics such as extracting data and matrices.

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