40
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) 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 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
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 rep(2, times=8), ncol=4, byrow=TRUE) #define column names and row names of matrix colnames(tab) A', 'B', 'C', 'D') rownames(tab) 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