# How to Create a Two Way Table in R (With Examples)

A two-way table is a type of table that displays the frequencies for two categorical variables.

For example, the following two-way table shows the results of a survey that asked 100 people which sport they liked best: baseball, basketball, or football.

The rows display the gender of the respondent and the columns show which sport they chose:

This tutorial provides several examples of how to create and work with two-way tables in R.

### Example 1: Create a Two Way Table from Scratch

The following code shows how to create a two way table from scratch using the as.table() function:

```#create matrix
data <- matrix(c(13, 23, 15, 16, 20, 13), ncol=3)

#specify row and column names of matrix
rownames(data) <- c('Male', 'Female')

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

#display table
data

Male         13         15       20
Female       23         16       13```

### Example 2: Create a Two Way Table from Data

The following code shows how to create a two-way table from a data frame:

```#create data frame
df <- data.frame(sport=c('Base', 'Base', 'Bask', 'Foot', 'Foot'),
gender=c('Male', 'Female', 'Male', 'Male', 'Female'))

#view data frame
df

#create two way table from data frame
data <- table(df\$gender, df\$sport)

#display two way table
data

Female    1    0    1
Male      1    1    1
```

### Example 3: Calculate Margin Sums of a Two Way Table

The following code shows how to calculate margin sums of a two-way table using the margin.table() function:

```#create matrix of data
data <- matrix(c(13, 15, 20, 23, 16, 13), ncol=3)
rownames(data) <- c('Male', 'Female')

#find sum of genders
margin.table(data, margin=1)

Male Female
49     51

#find sum of sports

margin.table(data, margin=2)

28         43         29
```

### Example 4: Visualize Two Way Table Frequencies

One way to visualize the frequencies in a two way table is to create a barplot:

`barplot(data, legend=True, beside=True, main='Favorite Sport by Gender')`

Another way to visualize the frequencies in a two way table is to create a mosaic plot:

```mosaicplot(data, main='Sports Preferences', xlab='Gender', ylab='Favorite Sport')
```

May 13, 2024
April 25, 2024
April 19, 2024
April 18, 2024

## One Reply to “How to Create a Two Way Table in R (With Examples)”

1. Heulwen Sweet says:

Good morning Zach,
I am writing to you from Melbourne, Australia. I really liked your explaining of two way tables but wanted to update it so my Deaf and signing students can access it. It is only for the purposes of education.