Tables are used to display a single categorical variable.
The data for these examples comes from the mtcars dataset.
my.table <- table(mtcars$gear, dnn="Gears"); # creates a table
my.table # Displays the table## Gears
## 3 4 5
## 15 12 5
my.table <- table(mtcars$gear, dnn="Gears"); # creates a table
addmargins(my.table); # Table with total## Gears
## 3 4 5 Sum
## 15 12 5 32
my.table <- table(mtcars$gear, dnn="Gears"); # creates a table
prop.table(my.table) # Divides table by table total## Gears
## 3 4 5
## 0.46875 0.37500 0.15625
my.table <- table(mtcars$gear, dnn="Gears"); # creates a table
round( prop.table(my.table), 4) # Rounded ## Gears
## 3 4 5
## 0.4688 0.3750 0.1562
Suppose you collected your own data and it looks something like this.
| Category | Count |
|---|---|
| A | 25 |
| B | 21 |
| C | 20 |
If the data is stored in a spreadsheet you could read the data in and save it as a variable. If it is not saved in a spreadsheet you may create a table by using the code below.
my.data <- c(rep("A", 25), rep("B", 21), rep("C", 20) )
table(my.data, dnn="Category")## Category
## A B C
## 25 21 20
There are many different ways to make a contingency table in R. Below is code to produce a Contingency table with different functions. The outputs are similar, but the underlying structures are very different.
selectlibrary(tidyverse) # loads select() and %>%
mtcars %>% select(gear) %>% table(dnn = "Gears")## Gears
## 3 4 5
## 15 12 5
withwith(mtcars, table(gear))## gear
## 3 4 5
## 15 12 5
xtabsxtabs( ~ gear , data = mtcars)## gear
## 3 4 5
## 15 12 5
mosaic# load the mosaic package to use tally()
library(mosaic)
tally( ~ gear , data=mtcars)## gear
## 3 4 5
## 15 12 5
dplyrlibrary(dplyr) # load the dplyr package to use %>%
mtcars %>% count(gear)## gear n
## 1 3 15
## 2 4 12
## 3 5 5
The kable() function in the knitr package is one of several functions that converts a standard table to a number of alternative formats. This is useful for creating fancier tables in documents and html pages. The xtable() function in the xtable package will also do this.
knitr::kable(my.table)| Gears | Freq |
|---|---|
| 3 | 15 |
| 4 | 12 |
| 5 | 5 |
Mathematicss, Computer Science, and Statistics Department Gustavus Adolphus College