How to Create a Table in R? (2024)

How to create a table in R? You can use the R base table() function to create a contingency table from various R objects such as vectors, data frames, and matrices. A contingency table is nothing but a cross-tabular data structure that displays the frequency of different combinations of factor levels, offering insights into the distribution and relationships within the data. In this article, I will discuss how to use the table() function and explore other functions and packages that can help in creating and manipulating tables in R.

Advertisem*nts

Key points-

  • The table() function is used to produce tables from raw data by counting the occurrences of unique values in one or more vectors.
  • By passing a vector to the table() function, you can create a frequency table that lists the frequency of each unique value.
  • You can create a contingency table by specifying columns of a data frame as arguments to the table() function.
  • The combination of two frequency tables is also known as contingency tables.
  • The table() function can handle NA values using the useNA parameter, allowing for the inclusion of NA counts in the table.
  • You can subset tables to focus on specific parts of the data.
  • Use the as.data.frame() function to convert a table object into a data frame for easier manipulation and analysis.
  • The xtabs() function is useful for creating more complex contingency tables from data frames, offering flexibility in tabulating data.
  • The tidyverse suite, particularly dplyr and tidyr, provides powerful tools for data manipulation and reshaping, making it easy to create and manipulate tables.

R Base table() Function

The table() function in R language is used to generate a categorical representation of data with the variable name and frequency in the form of a table. This function creates contingency tables, which count the combinations of factor levels. It is straightforward and effective for creating tables from vectors, data frames , and matrices to produce cross-tabulations of categorical data.

Syntax of table()

Following is the syntax of the table() function.

# Syntax of table() functiontable(x)

Parameters

  • x: ...: One or more vectors, data frames, or matrices. Each element contributes to the dimensions of the resulting table.

Return value

The table() function returns an object of class table, which is an array with named dimension names (dimnames). This array includes the frequency counts of the combinations of factor levels.

Create a Frequency Table using table()

You can create a frequency table from a vector using the base R table() function. By passing the vector into this function, it returns a frequency table, which is a list of objects displaying the frequency of each item in the table.

# Create a table using table() # Create a sample vectorprint("Given vector:")data <- c("A", "B", "C", "D", "E", "F")print(data)# Create a tableprint("Create table:")table_data <- table(data)print(table_data)print("Get the type:")print(class(table_data))

Yields below output.

How to Create a Table in R? (1)

Create a Contingency Table From a Data Frame

To create a contingency table from a data frame, pass the columns of the data frame into the table() function. This will return a contingency table where the values represent the frequency of the combinations of the given column values.

# Create a contingency table from data framedf <- data.frame(gender = c("Male", "Male", "Female", "Female", "Male", "Female"),product = c("A", "B", "A", "B", "A", "B"))print("Given data frame:")print(df)# Create a contingency tabletable_data <- table(df$gender, df$product)print("After creating a table:")print(table_data)print("Get the type of object:")print(class(table_data))

Yields below output.

How to Create a Table in R? (2)

As shown in the output above, the R table has been created from the data frame. In this table, the column names correspond to the unique values from the second column of the data frame, while the row names represent the unique values from the first column. The values within the table indicate the counts of each combination of gender and product.

Create Tables with NA Values

When creating tables, use the use NA = "ifany" parameter to handle NA values and include them in the table. Let’s create a data frame with NA values and pass its column values into the table() function to get a contingency table where the values represent the frequency of the combination of column values, including the occurrences of NA values.

# Create a data framedf <- data.frame( gender = c("Male", NA, "Female", "Female", "Male", NA), product = c("A", "B", "A", "B", "A", "B"))print("Given data frame:")print(df)# Create a contingency tabletable_data <- table(df$gender, df$product, useNA = "ifany")print("After creating a table:")print(table_data)print("Get the type of object:")print(class(table_data))

Yields below output.

# Output:[1] "Given data frame:" gender product1 Male A2 <NA> B3 Female A4 Female B5 Male A6 <NA> B[1] "After creating a table:" A B Female 1 1 Male 2 0 <NA> 0 2[1] "Get the type of object:"[1] "table"

Subset the Table

You can manipulate a table by subsetting the data based on column or row names. To do this, use square bracket notation ([]) with the table, specifying the rows before the comma and the columns after the comma in R tables.

For example, you can pass the specified column name into the square brackets along with the table to subset the table based on the desired criteria.

# Subset the table# Create a data framedf <- data.frame( gender = c("Male", "Male", "Female", "Female", "Male", "Female"), product = c("A", "B", "A", "B", "A", "B"))# Create a contingency tabletable_data <- table(df$gender, df$product)print("Create table:")print(table_data)# Subset the tablesubset_table <- table_data[,"A"]print("After subsetting the table:")print(subset_table)

Yields below output.

 # Output:Create table A B Female 1 2 Male 2 1[1] "After subsetting the table:"Female Male 1 2 

Convert Table to Data Frame

Alternatively, you can convert R tables into a data frame using the as.data.frame() function. Simply pass the table into the as.data.frame() function, which will transform the table object into a data frame, including one of the columns for frequency values.

# Convert table to data framedf1 <- as.data.frame(table_data)print("After converting the table to data frame:")print(df1)print("Get the type of object:")print(class(df1))

Yields below output.

# Output:[1] "After converting the table to data frame:" Var1 Var2 Freq1 Female A 12 Male A 23 Female B 24 Male B 1[1] "Get the type of object:"[1] "data.frame"

Create a Table using the xtabs Function

Similarly, you can use the base R xtabs() function to create contingency tables from data frames. By passing the columns of the data frame along with the data frame itself into this function, it will generate a table where the values represent the frequency of the combinations of the specified columns.

# Create table using xtabs()table_data <- xtabs(~ gender + product, data = df)print("After creating a table:")print(table_data)print("Get the type of object:")print(class(table_data))

Yields below output.

# Output:[1] "After creating a table:" productgender A B Female 1 2 Male 2 1[1] "Get the type of object:"[1] "xtabs" "table"

Using the tidyverse to Create Contingency Table in R

Use the tidyverse package to create and manipulate tables. Before using these functions, you need to install and load the package into your R environment. You can then use the %>%, count(), and pivot_wider() functions to generate tables from a given data frame.

# Create table using tidyverse package# Install and load tidyverse packagelibrary(tidyverse)# Create a data framedf <- tibble( gender = c("Male", "Male", "Female", "Female", "Male", "Female"), product = c("A", "B", "A", "B", "A", "B"))# Create a contingency tabletable_data <- df %>% count(gender, product) %>% pivot_wider(names_from = gender, values_from = n, values_fill = list(n = 0))print("After creating a table:")print(table_data)print("Get the type of object:")print(class(table_data))

Yields below output.

# Output:[1] "After creating a table:"# A tibble: 2 × 3 product Female Male <chr> <int> <int>1 A 1 22 B 2 1[1] "Get the type of object:"[1] "tbl_df" "tbl" "data.frame"

Using as.table() function to Create Tables

Finally, you can use the as.table() function to create tables from matrices. Passing a matrix into this function will generate a table where the values are the same as those in the given matrix.

# Create table using as.table() function # Create matrixdata <- matrix(1:8, ncol=4, byrow=TRUE)# Create column names and row names of matrixcolnames(data) <- c('A', 'B', 'C', 'D')rownames(data) <- c('F', 'G')# Create a tabletable_data <- as.table(data)print("Create table:")print(table_data)print("Get the type:")print(class(table_data))

Yields below output.

# Output:[1] "Create table:" A B C DF 1 2 3 4G 5 6 7 8[1] "Get the type:"[1] "table"

Conclusion

In this article, I have explained the table() function in R, including its syntax, parameters, and usage for creating and manipulating contingency tables from R objects like vectors, data frames, and matrices. Additionally, I have covered how to use other functions like xtabs(), as.table(), and the tidyverse package to generate contingency tables from R objects.

Happy Learning!!

How to Create a Table in R? (2024)

References

Top Articles
Asian-Kdolls.ch
Srw Wellness Llc
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
12 30 Pacific Time
Jami Lafay Gofundme
Litter-Robot 3 Pinch Contact & Dfi Kit
Greenbrier Bunker Tour Coupon
No Compromise in Maneuverability and Effectiveness
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 6093

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.