Check the measurement, then calculate

Day 11 — Data quality and evidence

Data Analysis in Life Sciences

About this lecture

A labmate exports the seedling measurements from the lab spreadsheet and sends you the file. You calculate the group means and email them to your supervisor. A week later someone notices that one plant appears twice and one length was typed in centimetres. R never complained: it calculates a precise-looking answer from whatever table it is given. How do you know the table is fit to calculate from?

Today you will:

  • inspect a raw file as text before turning it into numbers;
  • repair only what source evidence supports, in a script, keeping the original file unchanged;
  • keep an unknown value unknown, and count plant records and usable measurements separately;
  • save and re-check the cleaned file so that someone else can trace every change.

Week 3 is about describing data. The checked table and these habits carry into Days 12–15 and into the comparisons of week 4.

The problem: one slip changes the result

  • In the export, plant P21’s final length is 4.38. The source notebook says 43.8 mm: the value was typed in centimetres.
  • Left as it is, P21 “grew” −19.2 mm.
  • That one cell pulls the treated mean from 21.49 mm down to 18.21 mm.
  • R prints both numbers with the same confidence. Only a check against the source tells them apart.

Treated growth values with P21 left as 4.38 (one point far below zero, group mean 18.21 mm) and with P21 corrected to 43.8 mm (group mean 21.49 mm).

Keep the original; repair in a script

  • Never edit the raw CSV by hand. Keep it exactly as received.
  • Make each repair in day11-cleaning.R and write a new derived file.
  • For every changed value, the trail is: observation → evidence → action → check.
  • Then you, a supervisor or a reviewer can see each change, why it was made, and rerun it.

Preserve the raw CSV, explain the changes in a repair script, and recreate a separate clean CSV.

Inspect the entries as text first

> raw <- read_csv("data/seedlings-messy.csv", show_col_types = FALSE,
+                 col_types = cols(.default = col_character()),
+                 trim_ws = FALSE)
> dim(raw)
[1] 25  4
> unique(raw$treatment)
[1] "control"  "Control"  "treated"  "treated "
> raw |> count(plant_id) |> filter(n > 1)
# A tibble: 1 × 2
  plant_id     n
  <chr>    <int>
1 P01          2
  • dim(): 25 rows, 4 columns, but the study has 24 plants.
  • unique() lists each different value once: four spellings of two treatments. Reading every column as text (col_character()) and keeping spaces (trim_ws = FALSE) makes "treated " visible.
  • count() counts the rows for each plant ID; filter(n > 1) keeps IDs that occur more than once: P01.

Look at the rows that need a decision

> filter(raw, plant_id == "P01")
# A tibble: 2 × 4
  plant_id treatment initial_mm final_mm
  <chr>    <chr>     <chr>      <chr>
1 P01      control   25.7       44.3
2 P01      control   25.7       44.3
> filter(raw, plant_id %in% c("P06", "P18", "P21"))
# A tibble: 3 × 4
  plant_id treatment initial_mm final_mm
  <chr>    <chr>     <chr>      <chr>
1 P06      control   24.7       <NA>
2 P18      treated   18.7 mm    39.7
3 P21      treated   23.6       4.38
  • P01: two identical rows. The field notes say the import repeated it: one plant.
  • P06: no final length (<NA> = not available). The reading was never recorded.
  • P18: the initial length is text with a unit, 18.7 mm.
  • P21: final 4.38 is shorter than the start, 23.6. The notebook says 43.8 mm.
  • %in% keeps the rows whose ID is in the list.

A suspicious value is a question, not a verdict

  • 4.38 is not wrong because it is small. It is wrong because the notebook records 43.8 mm.
  • "18.7 mm" becomes the number 18.7 only after we confirm the unit is millimetres.
  • A very small or large value without source evidence stays in the data. Plants really do vary.
  • If you cannot decide, ask the person who recorded it, and note the open question.

Rulers show the same length expressed as 43.8 millimetres and 4.38 centimetres; only the source notebook justifies correcting P21.

Unknown is different from zero

  • P06’s final length was not recorded. Keep it as NA (not available).
  • A zero would claim the plant shrank to nothing: growth −24.7 mm (its initial length was 24.7 mm).
  • That invented value pulls the overall mean from 18.49 mm to 16.69 mm.
  • Do not copy a value from another file to fill the gap either. Report the plant as missing.

The overall mean growth is 18.49 mm when P06 is kept as missing, and 16.69 mm when its final length is invented as zero.

The repair, step by step

> 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)
> filter(cleaned, plant_id %in% c("P06", "P18", "P21"))
# A tibble: 3 × 5
  plant_id treatment initial_mm final_mm growth_mm
  <chr>    <chr>          <dbl>    <dbl>     <dbl>
1 P06      control         24.7     NA        NA
2 P18      treated         18.7     39.7      21
3 P21      treated         23.6     43.8      20.2
  • trimws() removes edge spaces and tolower() turns Control into control. if_else() changes only the named plant.
  • distinct() drops the identical second P01 row. parse_double() turns the text into numbers (<dbl>); the blank becomes NA.
  • P21 now grew 20.2 mm; P06’s growth stays unknown.

Count records and usable measurements separately

> nrow(cleaned)
[1] 24
> sum(is.na(cleaned$growth_mm))
[1] 1
> mean(cleaned$growth_mm)
[1] NA
> mean(cleaned$growth_mm, na.rm = TRUE)
[1] 18.48696
  • is.na() marks unknown values; sum() counts them: 1.
  • mean() gives NA: one value is unknown, so R will not guess.
  • na.rm = TRUE (“remove NA”) averages the 23 available growths. Report it as “n = 23 of 24 plants”.

Both groups retain twelve plant records; one control plant lacks a usable growth value, giving 11 available control growths and 12 treated.

Save, read back, and check the file on disk

> write_csv(cleaned, "output/seedlings-cleaned.csv")
> list.files("output")
[1] "seedlings-cleaned.csv"
> check_copy <- read_csv("output/seedlings-cleaned.csv",
+                        show_col_types = FALSE)
> nrow(check_copy)
[1] 24
> anyDuplicated(check_copy$plant_id)
[1] 0
> sum(is.na(check_copy$growth_mm))
[1] 1
  • write_csv() prints nothing. list.files() shows the new file in output/.
  • Reading it back checks the saved file, the one a colleague receives: 24 plants, no repeated ID (anyDuplicated() gives 0), one unknown growth.
  • Then restart R and rerun the whole script. The raw CSV still has 25 rows; the cleaned CSV has 24.

A new file is a new source to check

A second class sends data/seedlings-transfer.csv: 18 plants, 9 per group.

Before importing, write down what you expect: what one row is, which ID must be unique, column names, units, allowed labels. Then check and record what you observe.

  • No source note reports an error in this file, so no correction is justified.
  • An unusual value: inspect it, keep it, and ask the recorder.

Initial against final length for the eighteen transfer plants, coloured by control and treated group; a new study needs its own checks.

Summary

Concept Key fact
Inspect first Read as text (col_character(), trim_ws = FALSE); unique(), count() reveal labels and repeated IDs
Evidence A value is changed only when a source record supports it, never because it looks odd
Raw file Never edited; repairs live in a script that writes a separate derived file
Duplicates Compare all fields and the design; distinct() only for confirmed identical rows
Missing Unknown stays NA; a zero is a claim (P06 would “grow” −24.7 mm)
Counts 24 plant records, 23 usable growths; report the n behind every mean
Check Read the saved file back; restart R and rerun the script

Next (Day 12, variation): with a table we can trust, we describe how much individual plants differ from each other, not only their average.

Now: open the Day 11 exercises. Leave with day11-cleaning.R, output/seedlings-cleaned.csv and your cleaning notes.