How to Create Tables in R (With Examples)


There are two ways to quickly create tables in R:

Method 1: Create a table from existing data.

tab <- table(df$row_variable, df$column_variable)

Method 2: Create a table from scratch.

tab <- matrix(c(7, 5, 14, 19, 3, 2, 17, 6, 12), ncol=3, byrow=TRUE)
colnames(tab) <- c('colName1','colName2','colName3')
rownames(tab) <- c('rowName1','rowName2','rowName3')
tab <- as.table(tab)

This tutorial shows an example of how to create a table using each of these methods.

Create a Table from Existing Data

The following code shows how to create a table from existing data:

#make this example reproducible
set.seed(1)

#define data
df <- data.frame(team=rep(c('A', 'B', 'C', 'D'), each=4),
                 pos=rep(c('G', 'F'), times=8),
                 points=round(runif(16, 4, 20),0))

#view head of data 
head(df)

  team pos points
1    A   G      8
2    A   F     10
3    A   G     13
4    A   F     19
5    B   G      7
6    B   F     18

#create table with 'position' as rows and 'team' as columns
tab1 <- table(df$pos, df$team)
tab1

  A B C D
F 2 2 2 2
G 2 2 2 2

This table displays the frequencies for each combination of team and position. For example:

  • 2 players are on position ‘F’ on team ‘A’
  • 2 players are on position ‘G’ on team ‘A’
  • 2 players are on position ‘F’ on team ‘B’
  • 2 players are on position ‘G’ on team ‘B’

And so on.

Create a Table from Scratch

The following code shows how to create a table with 4 columns a 2 rows from scratch:

#create matrix with 4 columns
tab <- matrix(rep(2, times=8), ncol=4, byrow=TRUE)

#define column names and row names of matrix
colnames(tab) <- c('A', 'B', 'C', 'D')
rownames(tab) <- c('F', 'G')

#convert matrix to table 
tab <- as.table(tab)

#view table 
tab

  A B C D
F 2 2 2 2
G 2 2 2 2

Notice that this table is the exact same as the one created in the previous example.

Additional Resources

How to Loop Through Column Names in R
How to Create an Empty Data Frame in R
How to Append Rows to a Data Frame in R

Leave a Reply

Your email address will not be published.