# How to Create a Two-Way Table in R

How to Create a Two-Way Table in R, A two-way table is a type of table that displays the frequencies for two categorical variables.

## How to Create a Two-Way Table in R

In this article, we will explore how to create and work with two-way tables in R.

Example 1: Create a Two-Way Table from Scratch

To create a two-way table from scratch, we can use the `as.table()` function. Here is an example:

Biases in Statistics Common Pitfalls » finnstats

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

# Specify row and column names of matrix
rownames(data) <- c('Male', 'Female')
colnames(data) <- c('Baseball', 'Basketball', 'Football')

# 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

To create a two-way table from a data frame, we can use the `table()` function. Here is an example:

``````# Create a 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

To calculate the margin sums of a two-way table, we can use the `margin.table()` function. Here is an example:

``````# Create a matrix of data
data <- matrix(c(13, 15, 20, 23, 16, 13), ncol=3)
rownames(data) <- c('Male', 'Female')
colnames(data) <- c('Baseball', 'Basketball', 'Football')

# 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 using the `barplot()` function:

``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 using the `mosaicplot()` function:

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

## Conclusion

Creating and working with two-way tables in R can be done using various functions such as `as.table()`, `table()`, and `margin.table()`.

Additionally, visualizing the frequencies in a two-way table can be done using functions such as `barplot()` and `mosaicplot()`.

Calculating Autocorrelation in R » Data Science Tutorials