How to create a contingency table using datasets in base R?


A contingency table is a cross-tabulation that looks like a matrix. These tables can have different as well as equal number of columns and rows. If we want to create a contingency table using datasets in base R then table function can be used. For example, if we want to create a contingency table for cyl and gear column of mtcars data then it can be done as shown in the below example 1.

Example1

Live Demo

> head(mtcars)

Output

mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

Example

Live Demo

> table(mtcars$cyl,mtcars$gear)

Output

 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2

Example

Live Demo

> table(mtcars$vs,mtcars$gear)

Output

3 4 5
0 12 2 4
1 3 10 1

Example2

Live Demo

> head(CO2)

Output

Plant Type Treatment conc uptake
1 Qn1 Quebec nonchilled 95 16.0
2 Qn1 Quebec nonchilled 175 30.4
3 Qn1 Quebec nonchilled 250 34.8
4 Qn1 Quebec nonchilled 350 37.2
5 Qn1 Quebec nonchilled 500 35.3
6 Qn1 Quebec nonchilled 675 39.2

Example

Live Demo

> table(CO2$Plant,CO2$Type)

Output

Quebec Mississippi
Qn1 7 0
Qn2 7 0
Qn3 7 0
Qc1 7 0
Qc3 7 0
Qc2 7 0
Mn3 0 7
Mn2 0 7
Mn1 0 7
Mc2 0 7
Mc3 0 7
Mc1 0 7

Example3

Live Demo

> head(npk,20)

Output

block N P K yield
1 1 0 1 1 49.5
2 1 1 1 0 62.8
3 1 0 0 0 46.8
4 1 1 0 1 57.0
5 2 1 0 0 59.8
6 2 1 1 1 58.5
7 2 0 0 1 55.5
8 2 0 1 0 56.0
9 3 0 1 0 62.8
10 3 1 1 1 55.8
11 3 1 0 0 69.5
12 3 0 0 1 55.0
13 4 1 0 0 62.0
14 4 1 1 1 48.8
15 4 0 0 1 45.5
16 4 0 1 0 44.2
17 5 1 1 0 52.0
18 5 0 0 0 51.5
19 5 1 0 1 49.8
20 5 0 1 1 48.8

Example

Live Demo

> table(npk$N,npk$P)

Output

0 1
0 6 6
1 6 6

Live Demo

> table(npk$P,npk$K)

Output

0 1
0 6 6
1 6 6

Example

Live Demo

> table(npk$P,npk$K)

Output

0 1
0 6 6
1 6 6

Updated on: 06-Nov-2020

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements