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
# [1] 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
# [1] "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:

 

 

Additionally, you might want to have a look at the other articles on my homepage. You can find some interesting articles below.

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top