Table Names & Labels in R (2 Examples)
In this R programming tutorial you’ll learn how to change the names and labels of a table object.
Table of contents:
Let’s just jump right in:
Have a look at the following example data:
x <- c(LETTERS[1:3], LETTERS[2:5], "B") # Create example vector x # Print example vector #  "A" "B" "C" "B" "C" "D" "E" "B"
Have a look at the previous RStudio console output. It shows that our example data is a vector object containing different character letters.
Let’s create a frequency table object based on this vector:
my_tab <- table(x) # Create example table my_tab # Print example table # x # A B C D E # 1 3 2 1 1
The previous output shows our example table, i.e. a contingency table with the count of each vector element.
Let’s change the names and labels of this table object!
Example 1: Change Column Names of Table Object
This section illustrates how to adjust the column labels of a table object.
my_tab_new1 <- my_tab # Duplicate table names(my_tab_new1) <- paste0("col_", 1:5) # Change column names of table my_tab_new1 # Print updated table # col_1 col_2 col_3 col_4 col_5 # 1 3 2 1 1
The previous output shows that we have changed the column names of our table object to col_1, col_2, col_3, col_4, and col_5.
Example 2: Change Row Names of Table Object
In Example 2, I’ll show how to modify the row names of a table object using the row.names function.
Consider the following R syntax:
my_tab_new2 <- t(my_tab_new1) # Duplicate table row.names(my_tab_new2) <- "row_1" # Change row names of table my_tab_new2 # Print updated table # col_1 col_2 col_3 col_4 col_5 # row_1 1 3 2 1 1
As you can see, we have added the row name row_1 to our table.
Video & Further Resources
Some time ago, I have released a video on my YouTube channel, which shows the examples of this article. You can find the video below:
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.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may read the other articles on my website. A selection of articles can be found below:
- Rename a Column Name in R
- Get Column Names of Data Frame
- Remove Row & Column Names from Matrix
- Set Row & Column Names of Data with Unknown Dimension
- Assign Column Names Based On Existing Row
- Introduction to R
Summary: This tutorial has demonstrated how to modify, rename, and create the names and labels of a table in R. Please let me know in the comments section below, if you have further comments or questions. Furthermore, don’t forget to subscribe to my email newsletter in order to get updates on new tutorials.