Context:FIT2086_MOC · summarising categorical variables, where mean/sd are meaningless · the cat–cat half of Association Between Variables · extends R Toolkit (Cheatsheet) · studio data: heart.csv, Mushroom.csvProblem it solves: count the levels of a categorical variable, and detect whether two categorical variables are associated.
Quick Revision
🎯 Trigger: a column of labels (or numeric codes standing for labels) ➔ make it a factor, then table() it; two such columns ➔ table(a, b) for a contingency table.
⚡ Key Constraint: association is read from how the row distribution changes across columns, not from raw cell counts — a big cell in a big row means nothing. Convert to proportions before judging.
Reading it ➔ every odour except none is entirely one class ➔ odor is by far the strongest predictor of class in this dataset; knowing the odour almost determines edibility.
Contrast a weak variable ➔ table(mush$class, mush$cap.shape) splits convex1948/1708 and flat1596/1556 — close to the overall 52%/48% base rate ⟹ little association, though bell (404/48) leans edible and knobbed (228/600) leans poisonous.
margin = 1 rows sum to 1 · margin = 2 columns sum to 1 · omitted the whole table sums to 1 ➔ pick the margin that answers the question (“given the odour, how likely is poison?” = column-wise).
✍️ Practice
Practice 1: Load Mushroom.csv and cross-tabulate class against habitat. Which habitats would make you suspect a mushroom is poisonous?
Key move: compare each column against the 52% edible base rate — paths (136 vs 1008) and urban (96 vs 272) are strongly poisonous, meadows (256 vs 36) and waste (all edible) strongly edible. woods and grasses are near the base rate and carry little signal.
Practice 2: In heart.csv, tabulate heart disease by sex as proportions within each sex, so the two groups are comparable despite unequal sizes.
Key move: the raw counts (25 vs 114 “YES”) are incomparable because the groups differ in size (97 vs 206); row proportions give ≈0.26 vs ≈0.55, which is the actual comparison. margin = 1 is what makes unequal groups comparable.
⚠️ Common Mistakes
💡 Comparing raw counts across unequal groups ➔ a larger group produces larger cells everywhere; always prop.table(..., margin=) before claiming association.
💡 labels/levels is an assertion, not a lookup ➔ R applies whatever mapping you give it, silently. Get the coding backwards and every downstream table, plot and model is mislabelled while looking perfectly plausible — verify the codebook first.
💡 Forgetting stringsAsFactors = TRUE ➔ text columns load as plain character, so R will not treat them as categorical; specify it on everyread.csv of a dataset with labels.
💡 pie() for many levels ➔ human eyes compare angles badly; a pie with 9 slices (mushroom odor) hides exactly the differences the table makes obvious (see Data Visualisation (Chart Types)).