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 |
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") |
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 |
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) <- 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" |
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.
- How to Return a Row of a Data Frame Based On a Variable
- How to Apply the Same Function to Every Specified Data Table Variable
- Get Row Numbers where Data Frame Variable has Specific Value
- Transpose Data Matrix & Maintain First Variable as Column Names
- How to Add a New Variable Between 2 Data Frame Columns