Often you may want to print a table to the console in R to summarize the values in some dataset.
The following examples show how to print tables in R by using the table() and as.table() functions.
Example 1: Print One-Way Table from Data
Suppose we have the following data frame in R:
#create data frame df frame(team=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'), position=c('Guard', 'Guard', 'Forward', 'Guard', 'Forward', 'Forward', 'Guard', 'Guard', 'Forward'), points=c(14, 12, 15, 20, 22, 36, 10, 16, 19)) #view data frame df team position points 1 A Guard 14 2 A Guard 12 3 A Forward 15 4 B Guard 20 5 B Forward 22 6 B Forward 36 7 C Guard 10 8 C Guard 16 9 C Forward 19
We can use the table() function to summarize the count of each unique value in the position column:
#create table for 'position' variable
table1 #view table
table1
Forward Guard
4 5
From the table we can see that ‘Forward’ appears 4 times in the position column and ‘Guard’ appears 5 times.
This is referred to as a one-way table because it summarizes one variable.
Example 2: Print Two-Way Table from Data
Once again suppose we have the following data frame in R:
#create data frame df frame(team=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'), position=c('Guard', 'Guard', 'Forward', 'Guard', 'Forward', 'Forward', 'Guard', 'Guard', 'Forward'), points=c(14, 12, 15, 20, 22, 36, 10, 16, 19)) #view data frame df team position points 1 A Guard 14 2 A Guard 12 3 A Forward 15 4 B Guard 20 5 B Forward 22 6 B Forward 36 7 C Guard 10 8 C Guard 16 9 C Forward 19
We can use the table() function to summarize the count of each unique value in the team and position columns:
#create two-way table for 'team' and 'position' variables
table2 #view table
table2
Forward Guard
A 1 2
B 2 1
C 1 2
From the table we can see:
- There is 1 Forward on team A.
- There are 2 Guards on team A.
- There are 2 Forwards on team B.
And so on.
This is referred to as a two-way table because it summarizes the count of two variables.
Example 3: Print Table From Scratch
Suppose we already know the values that we’d like to fill in a table.
For example, suppose we want to create the following table in R that shows the results of a survey that asked 100 people which sport they liked best:
We can use the as.table() function in R to quickly create this table:
#create matrix data 3) #specify row and column names of matrix rownames(data) #convert matrix to table data table(data) #display table data Baseball Basketball Football Male 13 15 20 Female 23 16 13
The values in the table match the values from the table we saw earlier.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Create a Two Way Table in R
How to Create a Contingency Table in R
How to Use rbindlist in R to Make One Data Table from Many