Counts, shares, margins
◈ 9 cardstable(orders$prov) is AB 2 BC 3 ON 4 QC 3; round(prop.table(…) * 100, 1) is 16.7 25.0 33.3 25.0; sort(table(x), decreasing = TRUE) puts ON first. table(orders$prov, orders$channel) is the pivot Rows × Columns with Count; addmargins() adds the Sum row and column.
Counting categories
Module 4 counted provinces with COUNTIF, four times; Module 7 did it once with a pivot. table() is the one-call R version:
> table(orders$prov)
AB BC ON QC
2 3 4 3
Level names on the first line, counts on the second, alphabetical. Missing values are not counted unless you ask (useNA = "ifany").
Worked example — from counts to shares
A count answers "how many"; a share answers "how much of the whole". prop.table() divides a table by its total:
> prop.table(table(orders$prov))
AB BC ON QC
0.1666667 0.2500000 0.3333333 0.2500000
> round(prop.table(table(orders$prov)) * 100, 1)
AB BC ON QC
16.7 25.0 33.3 25.0
ON is a third of orders. The * 100 and round(…, 1) turn a proportion into a percentage to one decimal — the pivot's Show Values As → % of Grand Total, and the same 33.3 % Module 7 read off it.
A table sorts like a vector:
> sort(table(orders$prov), decreasing = TRUE)
ON BC QC AB
4 3 3 2
Most frequent first — the order a bar chart of counts should use.
Two variables: the pivot in one call
table() with two columns is Rows × Columns with Count. The first argument goes in the rows:
> table(orders$prov, orders$channel)
Online Store
AB 1 1
BC 2 1
ON 2 2
QC 1 2
ON placed 2 online and 2 in-store orders. addmargins() adds the totals the pivot shows by default:
> addmargins(table(orders$prov, orders$channel))
Online Store Sum
AB 1 1 2
BC 2 1 3
ON 2 2 4
QC 1 2 3
Sum 6 6 12
The Sum column is table(orders$prov) again; the Sum row is table(orders$channel) — 6 and 6. prop.table(t, 1) gives row shares (each province split by channel) and prop.table(t, 2) column shares, matching % of Row Total and % of Column Total.
Type the share and the margins, then reproduce the shares in Python
The code block counts with a dictionary and prints each province's share of 12 to one decimal, sorted — the same four numbers.
CRISP-DM: counts and shares are data understanding → explore data.