Calculate a variable, then show the observations

Day 8 — A new column and a figure, made by code

Data Analysis in Life Sciences

About this lecture

The seedling table is in R. The question is: how much did each plant grow, and did treated plants grow more? In a spreadsheet you would drag a formula down a new column and click a chart together. When a value is corrected next week, you would repeat every step by hand. Here, the new column and the figure come from a few lines of code that you simply run again.

Today you will:

  • add a calculated column (growth) with mutate();
  • keep the rows you want with filter() and the columns you want with select();
  • draw a labelled figure with ggplot(), where each point is one plant;
  • save the figure and the table as files other programs can open.

This builds on Day 7’s import. On Day 9 the code and the figure go into one report.

Growth is a new column, not an edit

First load the packages: library(readr), library(dplyr), library(ggplot2). (dplyr prints a note about “masked” functions; that is normal.)

> seedlings <- read_csv("data/seedlings.csv", show_col_types = FALSE)
> seedlings <- mutate(seedlings, growth_mm = final_mm - initial_mm)
> head(seedlings, 3)
# A tibble: 3 × 5
  plant_id treatment initial_mm final_mm growth_mm
  <chr>    <chr>          <dbl>    <dbl>     <dbl>
1 P01      control         25.7     44.3      18.6
2 P02      control         24.3     32.3       8  
3 P03      control         18       32.9      14.9
  • mutate() adds a column calculated from the others: now 5 columns. P01: 44.3 − 25.7 = 18.6 mm; P02: 8 mm.
  • The CSV file on disk is unchanged; only the table in R has the new column.

Which plants? Which columns?

> control_plants <- filter(seedlings,
+   treatment == "control")
> nrow(control_plants)
[1] 12
> growth_table <- select(seedlings,
+   plant_id, treatment, growth_mm)
> dim(growth_table)
[1] 24  3
  • filter() keeps rows (plants) that meet a condition: the 12 controls.
  • select() keeps the columns you name: all 24 plants, now 3 columns.

Treated rows are kept by filtering, then only the ID and growth columns are kept by selecting.

== asks “is it equal?”; <- stores. "control" is in quotes because it is a text label.

Read the steps from left to right

> longer_control <- seedlings |>
+   filter(treatment == "control") |>
+   filter(growth_mm > 15)
> longer_control
# A tibble: 7 × 5
  plant_id treatment initial_mm final_mm growth_mm
  <chr>    <chr>          <dbl>    <dbl>     <dbl>
1 P01      control         25.7     44.3      18.6
2 P04      control         22.2     40.2      18  
3 P06      control         24.7     40.7      16  
4 P07      control         21.2     38.3      17.1
5 P09      control         25.9     41.2      15.3
6 P10      control         23.2     41.9      18.7
7 P12      control         22.9     40.4      17.5
  • |> (the pipe) passes the table on to the next step. Read it as: take seedlings, then keep the controls, then keep growth above 15 mm.
  • The answer: 7 of the 12 control plants grew more than 15 mm. The + at the line starts is R saying “the instruction continues”.

A plot maps columns to positions

> size_plot <- ggplot(seedlings,
+     aes(x = initial_mm, y = final_mm,
+         colour = treatment)) +
+   geom_point(size = 2) +
+   labs(x = "Initial seedling length (mm)",
+        y = "Final seedling length (mm)",
+        colour = "Treatment") +
+   theme_minimal()
> size_plot

Typing size_plot draws the figure on the right in the Plots pane.

Final against initial length for the 24 seedlings, coloured by treatment, as drawn by size_plot.

aes() says which column goes where: x, y and colour. Each point is one plant. geom_point() draws points, labs() names the axes with units, and + adds each part.

Pick the plot that answers your question

  • Same plants, same x-axis, different y-axis.
  • Left: final length. Plants that started long tended to end long.
  • Right: growth. Here, plants that started long tended to grow less.
  • “Bigger at the end” is not “grew more”. Read the y-axis label before you interpret.

For the transfer study, initial length against final length (left) and against growth (right).

Show every plant’s growth

> growth_plot <- ggplot(seedlings,
+     aes(x = treatment, y = growth_mm)) +
+   geom_point(position = position_jitter(
+     width = 0.08, height = 0, seed = 8)) +
+   labs(x = "Treatment",
+        y = "Change in seedling length (mm)") +
+   theme_minimal()
> growth_plot
  • Jitter spreads points a little sideways so they don’t hide each other. height = 0: no value moves up or down.

Growth of each seedling by treatment, as drawn by growth_plot; the two groups overlap.

Controls grew 8.0–18.7 mm, treated plants 12.2–30.8 mm: treated tend higher, but the groups overlap.

Jitter must never change a measurement

Without and with horizontal jitter: the same growth values, spread sideways so that overlapping points become visible.
  • Sideways spread makes hidden points visible. The number of points and their heights stay the same.
  • Never add vertical jitter, and never drop points to make a plot look tidier.

Save files other programs can open

> ggsave("output/seedling-growth.png",
+        plot = growth_plot,
+        width = 6, height = 4, dpi = 150)
> write_csv(growth_table,
+           "output/seedling-growth.csv")
> list.files("output")
[1] "seedling-growth.csv" "seedling-growth.png"
> read_csv("output/seedling-growth.csv",
+          show_col_types = FALSE)
# A tibble: 24 × 3
   plant_id treatment growth_mm
   <chr>    <chr>         <dbl>
 1 P01      control        18.6
 2 P02      control         8  
...
  • ggsave() writes the plot as a PNG image; write_csv() writes the table as a CSV file. Both print nothing.
  • list.files("output") shows the two new files.
  • Reading the CSV back shows all 24 rows, as saved.
  • An existing file with the same name is replaced without asking. Never write into data/.

Worked example: the same steps on new data

> transfer <- read_csv(
+     "data/seedlings-transfer.csv",
+     show_col_types = FALSE) |>
+   mutate(growth_mm = final_mm - initial_mm)
> nrow(transfer)
[1] 18
> transfer$growth_mm[1]
[1] 15
> treated <- filter(transfer,
+   treatment == "treated")
> nrow(treated)
[1] 9

The first plant, T01: 40.3 − 25.3 = 15 mm. All 18 plants kept; 9 treated.

Growth of the 18 transfer-study seedlings by treatment, drawn with the same plotting code.

Same plotting code with transfer: controls 10.8–17.4 mm, treated 15.0–21.4 mm. Again they overlap.

Same steps for a lab calculation

> dilutions <- read_csv("data/dilutions.csv", show_col_types = FALSE) |>
+   mutate(stock_volume_ml = target_mmol_l * final_volume_ml / stock_mmol_l,
+          possible_by_dilution = target_mmol_l <= stock_mmol_l)
> select(dilutions, solution_id, stock_volume_ml, possible_by_dilution)
# A tibble: 4 × 3
  solution_id stock_volume_ml possible_by_dilution
  <chr>                 <dbl> <lgl>               
1 D01                     2.5 TRUE                
2 D02                     5   TRUE                
3 D03                    10   TRUE                
4 D04                   100   FALSE               
  • A stock is a solution of known concentration; diluting adds liquid up to a final volume. Stock volume = target × final volume / stock.
  • D04 needs 100 mL of stock for 50 mL of solution: impossible, because its target (200 mmol/L) is stronger than its stock (100 mmol/L). <= flags it FALSE; keep the row.

Summary

Step Function What to check
New column mutate(growth_mm = final_mm - initial_mm) One plant by hand (P01: 18.6 mm); the CSV is unchanged
Keep rows filter(treatment == "control") Row count (12)
Keep columns select(plant_id, treatment, growth_mm) Column count (3); all 24 plants remain
Chain steps |> (pipe) Run one step at a time when something breaks
Plot ggplot(aes(x, y)) + geom_point() + labs() One point = one plant; y-axis is the quantity you ask about; units in labels
Jitter position_jitter(width = 0.08, height = 0) Heights unchanged, no points lost
Save ggsave() for images, write_csv() for tables Open the files outside R

Next (Day 9, R Markdown): put the explanation, the code and the figure into one report that rebuilds itself from the data.

Now: open the Day 8 exercises. Leave with day08.R, output/seedling-growth.png and output/seedling-growth.csv, all recreated after restarting R.