How to Create Tables in R (9 Examples) | table() Function & Data Class (2024)

In this R programming tutorial you’ll learn how to create, manipulate, and plot table objects.

The content of the page is structured as follows:

1) Example Data

2) Example 1: Create Frequency Table

3) Example 2: Create Contingency Table

4) Example 3: Sort Frequency Table

5) Example 4: Change Names of Table

6) Example 5: Extract Subset of Table

7) Example 6: Create Proportions Table

8) Example 7: Draw Table in Barplot

9) Example 8: Convert Matrix to Table

10) Example 9: Check Class of Table Object

Note that this tutorial gives a brief overview on the usage of the table function in R. However, I have also published more detailed tutorials on the different topics shown in this tutorial. You may access these tutorials by clicking on the links within the corresponding sections.

Anyway, it’s time to dive into the programming part.

Example Data

The following data will be used as basem*nt for this R programming language tutorial:

data <- data.frame(x1 = rep(LETTERS[1:2], # Create example data frame each = 4), x2 = c(letters[1:3], letters[2:5], "b"))data # Print example data frame

How to Create Tables in R (9 Examples) | table() Function & Data Class (1)

Table 1 visualizes the output of the RStudio console and shows the structure of our exemplifying data – It is constituted of eight rows and two character columns.

Example 1: Create Frequency Table

This example shows how to make a frequency table in R.

For this task, we can apply the table() function to one of the columns of our example data frame:

The previous output shows the frequency counts of each value in the column x2. For instance, the letter a is contained once, and the letter b is contained three times.

Example 2: Create Contingency Table

The following R programming code explains how to make a contingency table, i.e. a table of multiple columns.

The following R code creates a two-way cross tabulation of our example data frame:

tab2 <- table(data) # Make contingency tabletab2 # Print contingency table# x2# x1 a b c d e# A 1 2 1 0 0# B 0 1 1 1 1

The previous output shows the frequency distribution among the two columns x1 and x2. For instance, the combination of A and a occurs once, and the combination of B and a appears not at all.

Example 3: Sort Frequency Table

This example explains how to order a table object.

For this example, we use the table object tab1 that we have created in Example 1 as basis.

We sort this table by applying the order function. Within the order function, we set the decreasing argument to be equal to TRUE, to show the values with the most occurrences first.

Have a look at the following R code:

tab3 <- tab1[order(tab1, decreasing = TRUE)] # Order tabletab3 # Print ordered table# b c a d e # 3 2 1 1 1

As you can see, the character b is shown first, since it occurs the most often in the data frame variable x2.

Example 4: Change Names of Table

In Example 4, I’ll demonstrate how to rename the elements of a table.

For this, we can apply the names and paste0 functions as illustrated in the following R code:

tab4 <- tab3 # Duplicate tablenames(tab4) <- paste0("x", 1:length(tab4)) # Change namestab4 # Print renamed table# x1 x2 x3 x4 x5 # 3 2 1 1 1

The previous output contains the same numeric values as the table that we have created in Example 3. However, the labels of those table cells have been changed.

Example 5: Extract Subset of Table

The code below shows how to return only a certain subset of a table object.

To achieve this, we use the table object tab1 that we have constructed in Example1 as basis. We can select a subset of this table object using a logical condition as shown below:

tab5 <- tab1[tab1 > 1] # Extract table subsettab5 # Print table subset# b c # 3 2

The previously shown table subset consists of all table elements that occur at least two times. All the other table elements have been removed.

Example 6: Create Proportions Table

In Example 6, I’ll explain how to create a proportions table (or probabilities).

For this task, we can apply the prop.table command to a table object (i.e. tab1) as illustrated in the following R syntax:

tab6 <- prop.table(tab1) # Make proportions tabletab6 # Print proportions table# a b c d e # 0.125 0.375 0.250 0.125 0.125

The previous output shows the proportions of each value in our data.

Example 7: Draw Table in Barplot

In Example 7, I’ll show how to plot a table object in a barchart.

To do this, we have to apply the barplot function to a table object:

barplot(tab1) # Draw table in plot

How to Create Tables in R (9 Examples) | table() Function & Data Class (2)

Figure 1 shows the output of the previous R code: A Base R bargraph showing the values in the table we have created in Example 1. The height of the bars corresponds to the occurrences of each value in our data set variable.

Example 8: Convert Matrix to Table

This example explains how to change the data type of a numeric matrix object to the table class.

For this example, we first have to create an exemplifying matrix:

mat <- matrix(1:12, ncol = 3) # Create example matrixmat # Print example matrix

How to Create Tables in R (9 Examples) | table() Function & Data Class (3)

As shown in Table 2, the previous R programming code has created a matrix object with four rows and three columns.

We can now use the as.table function to convert this matrix to the table class:

tab7 <- as.table(mat) # Convert matrix to tabletab7 # Print converted table# A B C# A 1 5 9# B 2 6 10# C 3 7 11# D 4 8 12

The previous output shows our new table object that we have created based on our input matrix.

Example 9: Check Class of Table Object

This example illustrates how to check whether a data object has the table class.

There are basically two alternatives on how to do this. Either, we can apply the class() function to return the class of a data object

class(tab7) # Return class of table# [1] "table"

…or we can apply the is.table function to return a logical indicator that shows whether our data object has the table class:

is.table(tab7) # Test if object is table# [1] TRUE

Both applications return the same result: The data object tab7 that we have created in Example 8 has the table class.

Video, Further Resources & Summary

In case you need further explanations on the examples of this tutorial, you might want to have a look at the following video on my YouTube channel. I’m showing the content of this article in the video.

The YouTube video will be added soon.

In addition, you may want to have a look at the other articles on my website. I have created a tutorial series that contains many additional instructions on how to use tables in R:

  • How to Create a Frequency Table
  • Contingency Table in R
  • prop.table Function in R
  • Weighted Frequency Table in R
  • Sort Table in R
  • Contingency Table Across Multiple Columns
  • Table by Group in R
  • Subset Table Object in R
  • Plot Table Object in R
  • Add Table to ggplot2 Plot
  • Print Table in R
  • Remove or Show NA Values in Table
  • How to Create a Pivot Table
  • Lookup Table in R
  • R Programming Examples

Summary: At this point of the article you should have learned how to apply the table command to calculate, construct, work, modify, and draw table objects in R programming. In case you have additional questions, don’t hesitate to tell me about it in the comments below.

4 Comments. Leave new

  • How to Create Tables in R (9 Examples) | table() Function & Data Class (4)

    ALI

    March 9, 2022 8:45 am

    Dear Joachim, Thanks for the great work!
    Could you please guide me on how to find the performance of the Bayesian Moving Average control chart using Posterior/prior distribution through ARL and SDRL as performance measures with the help of Monte Carlo Simulations?

    Reply
    • How to Create Tables in R (9 Examples) | table() Function & Data Class (5)

      Joachim

      March 10, 2022 8:24 am

      Hey Ali,

      Thank you for the kind comment! Unfortunately, I’m not an expert on this topic. However, I have recently created a Facebook discussion group where people can ask questions about R programming and statistics. Could you post your question there? This way, others can contribute/read as well: https://www.facebook.com/groups/statisticsglobe

      Regards,
      Joachim

      Reply
  • How to Create Tables in R (9 Examples) | table() Function & Data Class (6)

    Hussein

    March 26, 2023 1:40 pm

    thanks that was very useful

    Reply
    • How to Create Tables in R (9 Examples) | table() Function & Data Class (7)

      Matthias (Statistics Globe)

      March 27, 2023 10:26 am

      You’re welcome Hussein! Thanks for the feedback!

      Regards,
      Matthias

      Reply

Leave a Reply

How to Create Tables in R (9 Examples) | table() Function & Data Class (2024)

FAQs

How to create a table in R with data? ›

In R, these tables can be created using table() along with some of its variations. To use table(), simply add in the variables you want to tabulate separated by a comma.

What does the table () function do in R? ›

The table() function in R is a versatile tool that allows you to create frequency tables, also known as contingency tables, from categorical data. Its primary purpose is to summarize and organize the counts or frequencies of different unique values present within a vector, factor, or column of a data frame.

How to create a new column in R data table? ›

Method 1: Using :=

A column can be added to an existing data table using := operator. Here ':' represents the fixed values and '=' represents the assignment of values. So, they together represent the assignment of fixed values. Therefore, with the help of “:=” we will add 2 columns in the above table.

What is a data table in R? ›

data. table is an R package that provides a high-performance version of base R's data. frame with syntax and feature enhancements for ease of use, convenience and programming speed.

How to create a data table? ›

To create a data table in Excel, you can follow these steps:
  1. Select the cells you'd like to convert. First, open Excel and input the data you'd like to include in the table by entering it as organized rows and columns. ...
  2. Open the Create Table window. ...
  3. Customize parameters and create your table. ...
  4. Edit as needed.

How do you create a data list table? ›

Create and format tables
  1. Select a cell within your data.
  2. Select Home > Format as Table.
  3. Choose a style for your table.
  4. In the Create Table dialog box, set your cell range.
  5. Mark if your table has headers.
  6. Select OK.

What does the data () function help with in R? ›

data() was originally intended to allow users to load datasets from packages for use in their examples, and as such it loaded the datasets into the workspace . GlobalEnv . This avoided having large datasets in memory when not in use: that need has been almost entirely superseded by lazy-loading of datasets.

What is a () function in R? ›

Functions are “self contained” modules of code that accomplish a specific task. Functions usually take in some sort of data structure (value, vector, dataframe etc.), process it, and return a result. The general usage for a function is the name of the function followed by parentheses: function_name(input)

How does a table function work? ›

A table function returns a set of rows for each input row. The returned set can contain zero, one, or more rows. Each row can contain one or more columns. Table functions are sometimes called “tabular functions”.

How do I add a DataTable column? ›

To add the new column as the first column in your DataTable, you can follow these steps:
  1. Add Data Column: Use the Add Data Column activity to add the new column at the end of the DataTable. ...
  2. Reorder Columns: After adding the column, you can use the Assign activity to reorder the columns in the DataTable.
Oct 11, 2023

How to select columns in data table R? ›

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.

What is the difference between a DataFrame and a table? ›

Data frames are lists of vectors of equal length while data tables ( data. table ) is an inheritance of data frames. Therefore data tables are data frames but data frames are not necessarily data tables.

How to produce a table in R? ›

How to Create Tables in R?
  1. Syntax: as.table(data)
  2. Example: In this example, we will create a matrix and assign it to a table in the R language. ...
  3. Output: ...
  4. Syntax: table(dataframe$column_name, dataframe$column_name) ...
  5. Example: ...
  6. Output: 5 6 7 8 1 1 0 0 0 2 0 1 0 0 3 0 0 1 0 4 0 0 0 1.
Dec 27, 2021

What are the data types in R table? ›

Data Types in R

These data types can be numeric, integer, logical/boolean, character/string, vector, matrix, array, list, data-frame. It is useful to know the data type in order to know what functions can be performed on the object. To determine the type of data, you can use the class(), mode() or typeof() functions.

How to get data from table in R? ›

To access the table values, we can use single square brackets. For example, if we have a table called TABLE then the first element of the table can accessed by using TABLE[1].

How do you create a data collection table? ›

Here's how to make a data table by hand:
  1. Name your table. Write a title at the top of your paper. ...
  2. Figure out how many columns and rows you need.
  3. Draw the table. Using a ruler, draw a large box. ...
  4. Label all your columns. ...
  5. Record the data from your experiment or research in the appropriate columns. ...
  6. Check your table.
Mar 8, 2024

How do you save data as a table in R? ›

To save data as an RData object, use the save function. To save data as a RDS object, use the saveRDS function. In each case, the first argument should be the name of the R object you wish to save. You should then include a file argument that has the file name or file path you want to save the data set to.

How do you put data in a table? ›

To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis, followed by a list of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis.

How do I convert a data frame to a data table in R? ›

Method 1 : Using setDT() method

table object is a part of the data. table package, which needs to be installed in the working space. The setDT() method can be used to coerce the dataframe or the lists into data. table, where the conversion is made to the original dataframe.

References

Top Articles
Ravenlok All Figurines Guide: All Collectible Locations - Screen Hype
How to Find Groups in Telegram
3 Tick Granite Osrs
Bleak Faith: Forsaken – im Test (PS5)
Tmf Saul's Investing Discussions
Noaa Charleston Wv
Greedfall Console Commands
12 Rue Gotlib 21St Arrondissem*nt
Lifebridge Healthstream
Ingles Weekly Ad Lilburn Ga
Costco in Hawthorne (14501 Hindry Ave)
Atrium Shift Select
Truist Drive Through Hours
Culos Grandes Ricos
8 Ways to Make a Friend Feel Special on Valentine's Day
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
Healing Guide Dragonflight 10.2.7 Wow Warring Dueling Guide
Craigslist Deming
Cbs Trade Value Chart Fantasy Football
Hoe kom ik bij mijn medische gegevens van de huisarts? - HKN Huisartsen
Minecraft Jar Google Drive
Bitlife Tyrone's
ARK: Survival Evolved Valguero Map Guide: Resource Locations, Bosses, & Dinos
No Hard Feelings - Stream: Jetzt Film online anschauen
Energy Healing Conference Utah
Kayky Fifa 22 Potential
Att.com/Myatt.
Popular Chinese Restaurant in Rome Closing After 37 Years
Puretalkusa.com/Amac
Baldur's Gate 3: Should You Obey Vlaakith?
Costco Gas Hours St Cloud Mn
Reicks View Farms Grain Bids
Ficoforum
§ 855 BGB - Besitzdiener - Gesetze
The Collective - Upscale Downtown Milwaukee Hair Salon
This Is How We Roll (Remix) - Florida Georgia Line, Jason Derulo, Luke Bryan - NhacCuaTui
Select The Best Reagents For The Reaction Below.
Taylored Services Hardeeville Sc
The Posturepedic Difference | Sealy New Zealand
Restaurants Near Calvary Cemetery
Mobile Maher Terminal
Opsahl Kostel Funeral Home & Crematory Yankton
How to Destroy Rule 34
Jewish Federation Of Greater Rochester
Eastern New Mexico News Obituaries
Plead Irksomely Crossword
Shoecarnival Com Careers
Nimbleaf Evolution
The Bold and the Beautiful
Hughie Francis Foley – Marinermath
Craigslist Com Brooklyn
Noaa Duluth Mn
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 5985

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.