Assign Labels to Data Frame Variables in R (Example Code)

In this article, I’ll show how to add labels to the columns of a data frame in the R programming language.

Example Data

data(iris)                                        # Loading 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: Assigning Variable Labels to Data Frame Using label() Function of Hmisc Package

labs <- c(Sepal.Length = "1st variable label",    # Define labels
          Sepal.Width = "2nd variable label",
          Petal.Length = "3rd variable label",
          Petal.Width = "4th variable label",
          Species = "5th variable label")
install.packages("Hmisc")                         # Install Hmisc package
library("Hmisc")                                  # Load Hmisc
label(iris) <- as.list(labs[match(names(iris),    # Add variable labels
                                  names(labs))])
label(iris)                                       # Print variable labels
#         Sepal.Length          Sepal.Width         Petal.Length          Petal.Width              Species 
# "1st variable label" "2nd variable label" "3rd variable label" "4th variable label" "5th variable label"

Related Tutorials

You may find some related R programming tutorials on topics such as variables, matrices, and numeric values 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