Tables in R with table() and prop.table() (2024)

HOME DATA MANIPULATION IN R TABLE R

Data Manipulation in R Data transformation

Tables in R with table() and prop.table() (1)

The table function can be used for summarizing categorical data and generating absolute frequency and contigency tables. In this tutorial we will be exploring its syntax, various arguments, and practical examples to illustrate its utility in analyzing data. We will also explore the prop.table for relative frequency tables, xtabs for cross-tabulation, and addmargins to add margins to tables.

The table function

The table function in R is used to tabulate categorical data, counting the number of occurrences of each category. This function can create one-way tables, which provide the frequency of each category in a single variable, and two-way tables (or higher in high-dimensional arrays), which display the frequency distribution across two or more variables.

Syntax of the table function

The syntax of the function is the following:

table(..., exclude = if (useNA == "no") c(NA, NaN), useNA = c("no", "ifany", "always"), dnn = list.names(...), deparse.level = 1)

Being:

  • ...: one or more categorical variables or expressions to be tabulated.
  • exclude: optional argument specifying levels to be excluded from the table.
  • useNA: treatment of missing values. Possible options are "no" (default), "ifany" and "always"
  • dnn: character vector providing names for the resulting table.
  • deparse.level: controls how dnn is constructed by default. Read the documentation of the function for additional details.

One-way frequency tables

One-way tables represent the frequency distribution of a single variable. They are useful for understanding the distribution of categories within a variable. In order to create a table you will need to input a character vector, as illustrated below:

# Sample datadata <- c("B", "A", "C", "C", "A", "C", "B")# Create a simple frequency table for a categorical variableone_way_table <- table(data)one_way_table
dataA B C 2 2 3 

The previous ouput means that there are two elements that correspond to category "A", two correspond to "B" and three to "C". The previous table can be represented using a bar plot:

# Sample datadata <- c("B", "A", "C", "C", "A", "C", "B")# Create a simple frequency table for a categorical variableone_way_table <- table(data)# Plot the tablebarplot(one_way_table, col = 2:4, ylab = "Count")

Tables in R with table() and prop.table() (2)

The function provides an argument named exclude that can be used to exclude some categories from the output table. In the following example we are excluding "B".

# Sample datadata <- c("B", "A", "C", "C", "A", "C", "B")# Exclude specific levels from the frequency tabletable(data, exclude = "B")
dataA C 2 3

Sometimes, analyzing the presence of missing values is as important as the available data. The useNA argument can be leveraged to include NA values in the table. When set to "ifany" the table will also count the number of missing values.

# Sample datadata <- c("B", "A", NA, NA, "A", "C", "B")# Count NA values if anytable(data, useNA = "ifany")
data A B C <NA> 2 2 1 2 

When set to "always" the table will display the number of NA values even if there were none. This is very useful for data checking.

# Sample datadata <- c("B", "A", "A", "C", "B")# Count NA values even if there are nonetable(data, useNA = "always")
data A B C <NA> 2 2 1 0 

Two-way contingency tables

Two-way tables show the relationship between two categorical variables. They are crucial for examining the interactions between variables. This type of table can also be created with the table function, but you will need to input two character vectors of the same length instead of one, as illustrated below.

# Sample datagender <- c("Male", "Female", "Male", "Female", "Male")age_group <- c("Junior", "Senior", "Senior", "Junior", "Junior")# Create a two-way tabletwo_way_table <- table(gender, age_group)# View the tabletwo_way_table
 age_groupgender Junior Senior Female 1 1 Male 2 1

The previous data can be represented with a bar plot making use of the barplot function or any other similar function:

# Sample datagender <- c("Male", "Female", "Male", "Female", "Male", "Female")age_group <- c("Junior", "Senior", "Senior", "Junior", "Junior", "Senior")# Create a two-way tabletwo_way_table <- table(gender, age_group)# Plot the tablebarplot(two_way_table, col = 2:3, beside = TRUE, ylab = "Count")legend("topright", legend = c("Female", "Male"), fill = 2:3)

Tables in R with table() and prop.table() (3)

The prop.table function

The prop.table function takes a table created with table and converts it into a relative frequency table, also known as proportion table.

# Sample datagender <- c("Male", "Female", "Male", "Female", "Male")age_group <- c("Junior", "Senior", "Senior", "Junior", "Junior")# Create a two-way tabletwo_way_table <- table(gender, age_group)# Relative frequency tableprop.table(two_way_table)
 age_groupgender Junior Senior Female 0.2 0.2 Male 0.4 0.2

The function includes an argument named margin. Setting margin to 1 calculates proportions based on the sum of each row, whereas setting it to 2 calculates proportions based on the sum of each column.

# Sample datagender <- c("Male", "Female", "Male", "Female", "Male")age_group <- c("Junior", "Senior", "Senior", "Junior", "Junior")# Create a two-way tabletwo_way_table <- table(gender, age_group)# Relative frequency tableprop.table(two_way_table, margin = 1)
 age_groupgender Junior Senior Female 0.5000000 0.5000000 Male 0.6666667 0.3333333

The xtabs function

A function related to table is xtabs. The xtabs function allows creating contingency tables and it is specially useful for grouped data and when working with data frames. Unlike table, it uses a formula syntax, which allows for more complex specifications and is ideal for statistical analysis.

# Sample data framedf <- data.frame(x = c("G1", "G2", "G2", "G1", "G1", "G2"), y = c("A", "B", "B", "C", "A", "C"))# Contingency table with xtabstab <- xtabs(~ x + y, data = df)tab
 yx A B C G1 2 0 1 G2 0 2 1

An interesting feature of xtabs is that it can create weighted contingency tables. The following example illustrates how to input weights using the column w:

# Sample data framedf <- data.frame(x = c("G1", "G2", "G2", "G1", "G1", "G2"), y = c("A", "B", "B", "C", "A", "C"), w = c(0.1, 0.2, 0.2, 0.1, 0.1, 0.3))# Weighted contingency tabletab <- xtabs(w ~ x + y, data = df)tab
 yx A B C G1 0.2 0.0 0.1 G2 0.0 0.4 0.3

The addmargins function

The addmargins function in R is used to add row and/or column margins, usually representing sums or totals of the rows and/or columns to tables created with table or similar functions. The syntax of the function is the following:

addmargins(A, margin = NULL, FUN = sum, quiet = FALSE)

Being:

  • A: the input table.
  • margin: the desired margin. By default, the function calculates all margins, but when is set to 1, only row margins are calculated, and when set to 2, only column margins are calculated.
  • FUN: function to be applied to calculate the margins. It sums by default.
  • quiet: logical. If set to TRUE suppress messages.

When the function is applied to a table both margins will be added by default, counting the number of elements for rows and columns.

# Sample datagender <- c("Male", "Female", "Male", "Female", "Male")age_group <- c("Junior", "Senior", "Senior", "Junior", "Junior")# Create a two-way tabletwo_way_table <- table(gender, age_group)# Add marginsaddmargins(two_way_table)
 age_groupgender Junior Senior Sum Female 1 1 2 Male 2 1 3 Sum 3 2 5

However, if you only want to calculate the margins for rows or for columns you will need to set the margin argument to 1 or 2 depending on your needs.

# Sample datagender <- c("Male", "Female", "Male", "Female", "Male")age_group <- c("Junior", "Senior", "Senior", "Junior", "Junior")# Create a two-way tabletwo_way_table <- table(gender, age_group)# Add marginsaddmargins(two_way_table, margin = 2)
 age_groupgender Junior Senior Sum Female 1 1 2 Male 2 1 3

R version 4.3.2 (2023-10-31 ucrt)

Tables in R with table() and prop.table() (2024)

FAQs

Tables in R with table() and prop.table()? ›

Tables in R with table() and prop. table() The table function can be used for summarizing categorical data and generating absolute frequency and contigency tables. In this tutorial we will be exploring its syntax, various arguments, and practical examples to illustrate its utility in analyzing data.

What is the difference between table and prop table in R? ›

table is a function used to build a contingency table, which is a table that shows counts for categorical data, from one or more categories. prop. table is a function that accepts table output, returning proportions of the counts.

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.

What does the R function prop table () does in a crosstab? ›

Function prop. table() prints out the proportional values of the table that is given as an argument. We can make the table output more reader friendly by converting the proportional values into percentages (%).

How to create a table with two variables in R? ›

To create a two way table, simply pass two variables to the table() function instead of one. The output of a two-way table is a two-dimensional array of integers where the row names are set to the levels of the first variable and the column names are set to the levels of the second variable.

What does prop function do in R? ›

prop() calculates the proportion of a value or category in a variable.

What is the definition of prop table? ›

» PROPS TABLE. Definition: Table in convenient offstage area on which properties are prepared prior to a performance and to which they should be returned after use.

How do you use a table function? ›

To invoke a user-defined table function, reference the function in the FROM clause of an SQL statement where it is to process a set of input values. The reference to the table function must be preceded by the TABLE clause and be contained in brackets.

What is a contingency table in R? ›

Contingency tables are a fundamental tool in statistics, allowing researchers and data analysts to summarize and analyze the relationship between categorical variables. In the R programming language, creating and analyzing these tables can be accomplished with a few straightforward functions.

What does model tables do in R? ›

Computes summary tables for model fits, especially complex aov fits.

How to make a 3 way table in R? ›

In this method, we use the xtabs() function to construct a three-way table. We specify the formula ~ var1 + var2 + var3 to indicate the three categorical variables of interest (e.g., Year, Study_Method, Result).

What is the prop test function in R? ›

prop. test can be used for testing the null that the proportions (probabilities of success) in several groups are the same, or that they equal certain given values.

What is a crosstab in R? ›

The crosstab function calculates and prints a two-way frequency table. Given a data frame, a row variable, a column variable, and a type (frequencies, cell percents, row percents, or column percents) the function returns a table with. labeled rows and columns.

How to use table() in R? ›

To use table(), simply add in the variables you want to tabulate separated by a comma. Note that table() does not have a data= argument like many other functions do (e.g., ggplot2 functions), so you much reference the variable using dataset$variable.

How do you combine two tables into one in R? ›

Use full_join() , left_join() , right_join() and inner_join() to merge two tables together. Specify the column(s) to match between tables using the by option. Use anti_join() to identify the rows from the first table which do not have a match in the second table.

What is the difference between table and nested table? ›

Nested table collections are an extension of the index-by tables. The main difference between the two is that nested tables can be stored in a database column but index-by tables cannot. In addition some DML operations are possible on nested tables when they are stored in the database.

What is the difference between table and table schema? ›

Schema: Within a catalogue (or database), you have schemas. A schema is a collection of database objects, including tables, views, indexes, and procedures, grouped together. A schema is owned by a database user and shares the same name. Table: A table is the primary component of a schema.

What is the difference between table and Dataframe in R? ›

frame in R is similar to the data table which is used to create tabular data but data table provides a lot more features than the data frame so, generally, all prefer the data. table instead of the data.

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

View and Table both are integral parts of a relational database, and both terms are used interchangeably. The view is a result of an SQL query and it is a virtual table, whereas a Table is formed up of rows and columns that store the information of any object and be used to retrieve that data whenever required.

Top Articles
The Best Armies For Town Hall 5 In Clash of Clans
Clash of Clans: Best Attack Strategies for Town Hall Level 5 (2024)
Digitaler Geldbeutel fürs Smartphone: Das steckt in der ID Wallet-App
Pwc Transparency Report
Craigslist Free Stuff Merced Ca
Myra's Floral Princeton Wv
Harry Potter Magic Awakened best cards tier list – July 2023
Episode 163 – Succession and Legacy • History of the Germans Podcast
Boost Mobile 69Th Ashland
Cbs Week 10 Trade Value Chart
Exploring the Northern Michigan Craigslist: Your Gateway to Community and Bargains - Derby Telegraph
Word trip Answers All Levels [2000+ in One Page Updated 2023] » Puzzle Game Master
Allegheny Clinic Primary Care North
Humidity Yesterday At My Location
Craigsist Houston
'A Cure for Wellness', Explained
Annika Noelle Feet
Who is Ariana Grande? Everything You Need to Know
Craigslist Sfbay
Minnesota Gophers Highlights
Carly Carrigan Family Feud Instagram - Carly Carrigan Home Facebook : The best gifs for carly family feud.
Gas Buddy Prices Near Me Zip Code
COUNTRY VOL 1 EICHBAUM COLLECTION (2024) WEB [FLAC] 16BITS 44 1KHZ
Secret Stars Sessions Julia
Amex Platinum Cardholders: Get Up to 10¢ Off Each Gallon of Gas via Walmart Plus Gas Discount
Craigslist Eugene Motorcycles
Fastest Lovakengj Favour
Oscillates Like A Ship
Craftybase Coupon
Gw2 Blue Prophet Shard
02080797947
Welcome To Vioc Pos
No hard feelings: cómo decir "no" en inglés educadamente y sin herir sensibilidades
Hose Woe Crossword Clue
Dfw Rainfall Last 72 Hours
VMware accompagne ses partenaires et soutient leur transformation en faisant évoluer son programme « VMware Partner Connect » - Broadcom News & Stories - Français
Amarillos (FRIED SWEET PLANTAINS) Recipe – Taste Of Cochin
Obituaries Cincinnati Enquirer
Dying Light Nexus
Strange World Showtimes Near Andover Cinema
Mygxo Gxo Com Employee Login
Theatervoorstellingen in Roosendaal, het complete aanbod.
Z93 Local News Monticello Ky
Urgent Care Pelham Nh
Erica Mena Net Worth Forbes
Water Temperature Robert Moses
Rune Factory 5 Dual Blade Recipes
Craigslist Farm And Garden Atlanta Georgia
Akc Eo Tryouts 2022
A Man Called Otto Showtimes Near Cinemark Palace 20
Ideological variation in preferred content and source credibility on Reddit during the COVID-19 pandemic
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 6450

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.