Extract Values & Names from table Object in R (2 Examples)
This article illustrates how to extract the first row and the table names from an object with the table() class in the R programming language.
The content of the page is structured as follows:
So let’s get started:
Creating Example Data
The first step is to construct some example data:
set.seed(652955) # Create example table my_tab <- table(sample(letters[1:5], 100, replace = TRUE)) my_tab # Print example table # # a b c d e # 21 15 16 30 18
The previous output of the RStudio console illustrates that our example data is a table object created by the table() function. Our example table consists of one row and five columns.
Example 1: Extract Values from table Object
This example illustrates how to return the values contained in our table object, i.e. the first row of the table.
For this, we can use the as.numeric function as shown below:
tab_values <- as.numeric(my_tab) # Extract values tab_values # Print values #  21 15 16 30 18
The RStudio console shows the output of the previous R code. We have created a vector object consisting of the values of the first row of our input table.
Example 2: Extract Names from table Object
In this example, I’ll show how to select only the names of our table object.
For this task, we can use the names() function as shown below:
tab_names <- names(my_tab) # Extract names tab_names # Print names #  "a" "b" "c" "d" "e"
Video, Further Resources & Summary
Do you need further explanations on the examples of this post? Then you might want to have a look at the following video tutorial of my YouTube channel. I’m explaining the R codes of this tutorial in the video:
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.
Additionally, you might want to have a look at the other articles on my homepage. You can find some interesting articles below.
- Extract Year & Month from yearmon Object in R
- Extract Hours, Minutes & Seconds from Date & Time Object
- Extract Values from Matrix by Column & Row Names
- All R Programming Tutorials
To summarize: This tutorial has shown how to extract information from table objects (i.e. the data type “table”) in the R programming language. If you have any additional questions, don’t hesitate to let me know in the comments section.
Statistics Globe Newsletter