Missing Value Treatment
In Lesson 3 you met one blank cell, the unlogged Bagel sale, and patched it with na.rm = TRUE. Real data is never that tidy. Maya ran a quick exit survey one busy morning, twelve customers, five questions each, and came back with a table full of holes: a spend she never recorded, a rating the tablet ate, tips people simply would not say.
The wrong move is to delete every row with a blank and carry on. As you will see, that throws away two thirds of Maya's survey and quietly biases what is left. This lesson is about treating those holes honestly.
By the end you will be able to:
- Find and count missing values, and see how far the damage spreads
- Name why data goes missing (the three mechanisms: MCAR, MAR, MNAR)
- Choose between dropping and filling, and say how each choice bends the answer
Prerequisites: Lessons 1 to 3 of this course, so you know tidy data, the dplyr verbs and the pipe, and group_by / summarise with na.rm. Everything new is defined as it appears.
Find the holes before you fix them
Here is Maya's survey. Each lesson starts in a fresh R session, so we build the table right here (run this once). A blank answer is stored as NA, which R reads as "a value exists but I do not know it". One column carries each kind of hole, and we will return to that on purpose.
is.na(x) is the workhorse: it returns TRUE wherever a value is missing. Wrap it in sum() to count blanks, and colSums() to count them per column:
So nine cells are blank: three spends, two ratings, four tips. The dplyr way says the same thing, one verb per column:
Counting per column hides something, though. The real question is how many whole rows are usable. complete.cases() flags the rows with no blank anywhere:
Only four of the twelve customers, Ana, Finn, Ivy and Kim, answered every question. Nine scattered blanks have spoiled two thirds of the rows.