Day 8 — Turn measurements into a useful figure

Lecture slides · Quiz · Weekly revision

Today’s question

How much did each seedling grow, and did the treated plants grow more than the controls? The table only holds the start and end lengths, so today you calculate growth as a new column, pick out the plants and columns you need, and draw a figure in which every plant is a point. All of it is code in a script, so a corrected value later only means running the script again.

Start a script called day08.R in the project folder.

Save today: day08.R, output/seedling-growth.png and output/seedling-growth.csv.

Growth as a new column

library(readr)
library(dplyr)
library(ggplot2)
seedlings <- read_csv("data/seedlings.csv", show_col_types = FALSE)
seedlings <- mutate(seedlings, growth_mm = final_mm - initial_mm)
head(seedlings)

dplyr and ggplot2 are packages, like readr on day 7. mutate() adds a column calculated from the others, here final minus initial length for each plant, and we store the result under the old name seedlings. The table in R now has a fifth column; the CSV file on disk is unchanged. Check the first plant by hand: P01 grew 44.3 − 25.7 = 18.6 mm.

Growth and final length answer different questions. final_mm says how big a plant ended up; growth_mm says how much it changed. A plant that started big can end big and still have grown little.

Choosing plants and columns

filter() keeps the rows (plants) that meet a condition, and select() keeps the columns you name:

control_plants <- filter(seedlings, treatment == "control")
growth_table <- select(seedlings, plant_id, treatment, growth_mm)

control_plants has 12 rows, the control plants. growth_table has all 24 rows but only 3 columns. Note the double ==: it asks “is this equal?”, while <- stores. "control" is in quotes because it is a text label and must be spelt exactly as in the data.

Several steps can be chained with the pipe |>, which passes the table on to the next function. Use it to find out how many control plants grew more than 15 mm:

longer_control <- seedlings |>
  filter(treatment == "control") |>
  filter(growth_mm > 15)
nrow(longer_control)

Read it as “take seedlings, then keep the controls, then keep those that grew more than 15 mm”. 7 of the 12 control plants did. If a chain gives a surprising answer, run it one step at a time.

Did longer seedlings end longer?

ggplot() draws a figure from a table. aes() says which column goes where:

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

Each point is one plant, coloured by its group. + adds a part to the figure: geom_point() draws the points, labs() names the axes with their units, and theme_minimal() gives a plain background. A + at the end of a line tells R that the instruction continues on the next line.

The points form a loose cloud: seedlings that started longer ended only slightly longer on average. The treated points (final lengths up to 54.8 mm) sit mostly above the controls. But this figure shows final size, not growth.

Growth in each group

To answer the question about growth, put the group on the x-axis and growth on the y-axis:

growth_plot <- ggplot(seedlings, aes(x = treatment, y = growth_mm)) +
  geom_point(position = position_jitter(width = 0.08, height = 0, seed = 8),
             alpha = 0.8) +
  labs(x = "Treatment", y = "Change in seedling length (mm)") +
  theme_minimal()
growth_plot

Points with similar values would hide each other, so jitter moves them a little sideways. height = 0 makes sure no point moves up or down, so every growth value stays exactly as measured, and seed = 8 makes the sideways spread the same every time you run it.

Growth of each seedling by treatment; the groups overlap.

The controls grew between 8.0 and 18.7 mm and the treated plants between 12.2 and 30.8 mm. Treated plants tended to grow more, but the groups overlap: P17 (treated, 12.2 mm) grew less than most controls. Whether a difference of this size could be chance is a question for week 4; today we describe what we see.

Saving the figure and the table

ggsave("output/seedling-growth.png", plot = growth_plot,
       width = 6, height = 4, dpi = 150)
write_csv(growth_table, "output/seedling-growth.csv")

ggsave() writes the figure as a PNG image, and write_csv() writes the table as a CSV file, both into the project’s output/ folder. An existing file with the same name is replaced without asking, so never write into data/. Open both files from the file manager to check they are there.

Assigning a plot to a name does not show it; type the name, e.g. growth_plot, to print it. If saving fails, dir.exists("output") should say TRUE. If R says a column is not found, check names(seedlings) and rerun the mutate() line.

Your own figures

Add these to day08.R.

  1. Calculate P02’s growth by hand and compare it with the table: 32.3 − 24.3 = 8.0 mm, the smallest growth in the experiment.
  2. Use filter() and select() to make a table treated_growth with only the treated plants’ IDs and growth, and save it as output/treated-growth.csv. It has 12 rows and 2 columns.
  3. Draw initial length against growth, with both axes labelled in mm, to find out whether plants that started longer also grew more. They did not: if anything, the longer seedlings grew slightly less. Or do the yield task below.
  4. Restart R and run the whole script. The saved files should be recreated and still open.

Alternative: which protocol gives a better yield?

The file data/organic-recovery.csv records twelve runs of a chemical synthesis, six with a standard and six with a modified protocol. For each run, theoretical_mass_g is the largest possible product mass and isolated_mass_g the dry product collected, both in g; assume the product is pure. Runs started at different scales, so compare percentage yields rather than masses:

organic <- read_csv("data/organic-recovery.csv", show_col_types = FALSE)
organic <- mutate(organic,
                  yield_percent = 100 * isolated_mass_g / theoretical_mass_g)
head(organic)

The first run, Y01, collected 0.62 g of a possible 1.00 g: 62%. Draw a plot with protocol on the x-axis and yield_percent on the y-axis, labelled “Isolated product yield (%)”, using the same jitter as above, to find out which protocol gave higher yields. The standard runs gave 62–74% and the modified runs 72–82%. Save the table as output/organic-yields.csv and the plot as output/organic-yields.png.

A second class’s data

Day 7’s 18-plant study in data/seedlings-transfer.csv asks the same question with new plants. Start day08-transfer.R and repeat the workflow there.

  1. Read the file into transfer, add growth_mm with mutate(), and check one plant by hand: T01 grew 40.3 − 25.3 = 15.0 mm. The table still has 18 rows: adding a column does not remove plants.
  2. Make transfer_growth with ID, treatment and growth (18 rows), and transfer_treated with the treated plants only (9 rows).
  3. Draw initial against final length, and initial against growth, to find out whether plants that started longer grew more in this study. They ended longer, but they grew less: two figures of the same plants, two different answers, because the y-axes measure different things.
  4. Draw growth by group with the jitter from above. The controls grew 10.8–17.4 mm and the treated plants 15.0–21.4 mm, so again the groups overlap. Try changing only width in position_jitter(): the points move sideways, but no growth value changes.
  5. Save output/transfer-growth.csv, output/transfer-treated.csv, output/transfer-growth.png and output/transfer-size.png. Below the growth figure in your script, write a comment that could serve as its caption: what one point is, what the y-axis measures in which unit, and what you see.

Filter on the label, treatment == "treated", spelt exactly as in the data. There should be 9 rows; check table(transfer$treatment).

Which dilutions are possible?

A stock is a solution of known concentration. To dilute it, you take some stock and add liquid until you reach the final volume you want; the amount of dissolved substance stays the same. So the stock volume you need is

stock volume = target concentration × final volume / stock concentration.

With both concentrations in mmol/L and the final volume in mL, the stock volume comes out in mL. The file data/dilutions.csv lists four requested dilutions.

  1. Work out D02 by hand first: stock 500 mmol/L, target 50 mmol/L, final volume 50 mL gives 50 × 50 / 500 = 5 mL of stock. Then read the file into dilutions and use mutate() to add stock_volume_ml for every row. You get 2.5, 5, 10 and 100 mL.
  2. D04 asks for 100 mL of stock to make 50 mL of solution, which is impossible. Its target, 200 mmol/L, is stronger than its stock, 100 mmol/L, and adding liquid can only make a solution weaker. Add a column that flags this: possible_by_dilution = target_mmol_l <= stock_mmol_l (<= means “less than or equal to”). It is TRUE for D01–D03 and FALSE for D04.
  3. Save the whole table, D04 included, as output/dilution-check.csv, so the impossible request stays on record. Then use filter(possible_by_dilution) to keep the three possible ones and plot their final volume against stock volume, both in mL. The points lie on a straight line, because for the same stock and target the stock volume is proportional to the final volume.
  4. In reports/dilution-interpretation.txt, explain in two or three sentences why D04 is impossible, and the difference between “bring to 50 mL in total” and “add 50 mL of liquid”.

Check your understanding

filter() keeps rows, so it selects plants. select() keeps columns, so it selects variables such as growth_mm.

Growth is calculated from the recorded lengths. Keeping them lets anyone check the calculation, for example P02: 32.3 − 24.3 = 8.0 mm.

Keep: day08.R, your derived tables and figures in output/. If you chose the yield task, keep the two organic-yields files as well. Next: put explanation and code in one report.