Day 11 — Can we trust this table?

Lecture slides · Quiz · Weekly revision

Today’s question

A labmate has exported the seedling measurements from the lab spreadsheet into data/seedlings-messy.csv. Before calculating anything you want to know whether the file really holds 24 plants with sensible lengths. R will calculate a mean from any table, so the checking is up to you. Today you inspect the export, repair what the source records support, and save a cleaned copy while the raw file stays unchanged.

The study itself is described in the data dictionary. The source records for this export are in data/field-notes.txt; read them before you start.

Save today: day11-cleaning.R in the project root, output/seedlings-cleaned.csv and output/cleaning-notes.txt.

Reading every column as text

Start day11-cleaning.R with:

library(readr)
library(dplyr)
raw <- read_csv("data/seedlings-messy.csv", show_col_types = FALSE,
                col_types = cols(.default = col_character()), trim_ws = FALSE)
dim(raw)

Normally read_csv() guesses which columns hold numbers. Here cols(.default = col_character()) reads every column as text, so an odd entry stays exactly as it was typed, and trim_ws = FALSE keeps any spaces at the start or end of a value. dim() gives 25 rows and 4 columns, although the study has 24 plants.

Is any plant in the file twice?

Use count() to find out which plant IDs appear more than once, then look at those rows:

raw |> count(plant_id) |> filter(n > 1)
filter(raw, plant_id == "P01")

count() counts the rows for each ID and filter(n > 1) keeps the repeated ones. P01 appears twice, and its two rows are identical in every column. The study has one row per plant, and the field notes confirm that the second row is an accidental repeat of the import, so one of them can go. In a design with one row per time point a repeated ID would be normal, which is why you compare whole rows and the design before removing anything.

Which treatment labels are used?

Use unique() to find out how the treatment was written:

unique(raw$treatment)

There are four spellings: "control", "Control", "treated" and "treated " with a space at the end. R treats them as four different groups, so a group summary would give four rows instead of two. According to the field notes, P03’s Control means control and P15’s trailing space is an export mistake.

Are the lengths plausible?

Use filter() with %in% to look at the plants the field notes mention:

filter(raw, plant_id %in% c("P06", "P18", "P21"))

%in% keeps the rows whose ID is in the listed set. P18’s initial length is the text 18.7 mm, and the notes confirm it was measured in millimetres. P21’s final length is 4.38, much shorter than its initial 23.6 mm; the source notebook records 43.8 mm, so the value was typed in centimetres. P06 has no final length, and the notes say that reading is unavailable.

A value is changed only when a source record supports the change. A small or large value on its own is not a reason, because plants really do vary.

Repairing a copy in code

cleaned <- raw |>
  mutate(treatment = tolower(trimws(treatment)),
         initial_mm = if_else(plant_id == "P18", "18.7", initial_mm),
         final_mm = if_else(plant_id == "P21", "43.8", final_mm)) |>
  distinct() |>
  mutate(initial_mm = parse_double(initial_mm),
         final_mm = parse_double(final_mm),
         growth_mm = final_mm - initial_mm)

Each line carries out one sentence of the field notes. trimws() removes the spaces around a value and tolower() turns Control into control. if_else(condition, yes, no) replaces a value only in the row of the named plant. distinct() removes rows that are identical in every column, which here is the second P01. parse_double() then turns the checked text into numbers, and P06’s empty final length becomes NA, R’s code for a missing value. The CSV file is never edited, so anyone can rerun the script and see every repair.

Does the cleaned table have 24 plants?

Use nrow(), anyDuplicated() and sum(is.na()) to find out whether the repair left one row per plant and how many growth values are missing:

nrow(cleaned)
anyDuplicated(cleaned$plant_id)
sum(is.na(cleaned$growth_mm))
cleaned |> count(treatment)
write_csv(cleaned, "output/seedlings-cleaned.csv")

You should get 24 rows, 0 (no ID is repeated), 1 missing growth value, and 12 plants in each group. So the control group has 12 plants but only 11 usable growth values. write_csv() saves the cleaned table as a new file next to the other outputs.

Why P06 stays missing

Use mean() to find out the average growth of all plants:

mean(cleaned$growth_mm)
mean(cleaned$growth_mm, na.rm = TRUE)

The first line gives NA: one value is unknown, and R will not guess. With na.rm = TRUE (“remove NA”) R averages the 23 available values and gives 18.49 mm, which you report as the mean of 23 of the 24 plants.

Writing 0 for P06’s final length would claim a measurement nobody made. P06 started at 24.7 mm, so it would “grow” −24.7 mm and pull the overall mean down to 16.69 mm.

Look at filter(raw, plant_id == "P01") before using distinct(). Do not use distinct(plant_id, .keep_all = TRUE): it keeps the first row for each ID and throws away a second row even when the two disagree. Disagreeing records need investigation.

Checking your repairs

  1. Add a comment above each repair in day11-cleaning.R naming the field-note entry behind it. Then use filter(cleaned, plant_id %in% c("P06", "P18", "P21")) to find out whether those plants now have the values the notes give. You should see P18 with initial length 18.7, P21 with final length 43.8, and P06 with final length NA.
  2. Use group_by(treatment) and summarise(mean(growth_mm, na.rm = TRUE)) on cleaned to find out how much each group grew on average. Control gives 15.21 mm (11 plants) and treated 21.49 mm (12 plants).
  3. How much would the P21 slip have mattered? Make a copy in which P21 keeps the typed value: slipped <- mutate(cleaned, final_mm = if_else(plant_id == "P21", 4.38, final_mm), growth_mm = final_mm - initial_mm), and summarise it the same way. The treated mean drops to 18.21 mm, because P21 now “grew” −19.2 mm.
  4. Make wrong_zero_example in the same way, with P06’s final length set to 0, and use mean(wrong_zero_example$growth_mm) to find out what the invented zero does to the overall mean. You should get 16.69 mm instead of 18.49 mm.
  5. Use read_csv("data/seedlings-messy.csv", show_col_types = FALSE) with its default settings and str() to find out what R would have made of this file without the text import. The trailing space is silently removed, so only three labels remain, and initial_mm becomes a text column (chr) because of the single 18.7 mm entry, so no mean can be calculated from it.
  6. Write output/cleaning-notes.txt with one line per problem: the plant, what you saw, the evidence, and what you did. End with the plant whose measurement is unknown. Then restart R (Session → Restart R), rerun the whole script, and use nrow() to confirm that the raw file still has 25 rows and output/seedlings-cleaned.csv has 24.

A second class’s data

Another class has sent data/seedlings-transfer.csv: 18 seedlings, nine in each group, measured seven days apart like ours. They sent no field notes. Is the file ready to use? Start a new script, day11-transfer.R.

  1. Use dim(), count(plant_id), unique(treatment) and sum(is.na()) to find out whether the file has one row per plant, two clean labels and complete lengths. You should find 18 rows, no repeated ID, only control and treated, and no missing values.
  2. Use mutate() to calculate growth_mm and find out how much T01 grew. Check it by hand: 40.3 − 25.3 = 15.0 mm. Save the table with growth as output/day11-transfer-growth.csv.
  3. Write a short handover note, output/day11-transfer-audit.txt, saying what you checked and what you found. Since nothing was wrong and there are no source records, no value was changed. If a value had looked odd, you would keep it and ask the recorder.

Check your understanding

A source record, such as the notebook entry for P21. A check only raises the question; the evidence answers it. A very small or large value may be real and is kept unless a record shows it was entered wrongly.

No. The extra row was the identical second P01, removed because the field notes confirm the duplicate import. All 24 plants are still there; P06 is kept with an unknown final length.

Keep: day11-cleaning.R, output/seedlings-cleaned.csv and output/cleaning-notes.txt. Next: describe variation.