Day 6 — Let R keep track of a calculation

Lecture slides · Quiz · Weekly revision

Today’s question

A seedling was 20 mm long at the start of an experiment and 37 mm long at the end. How much did it grow, and how much did three, then four, plants grow? Today you write the answer as a saved R script, so that you can run the whole calculation again whenever a value changes. The measurements are simulated teaching data.

Open the course project by double-clicking introcomputing.Rproj, as on day 5. Keep the R reference sheet open while you work.

Save today: day06.R in the project folder.

A first calculation

Type these lines in the Console, pressing Enter after each:

37 - 20
37 / 20

R prints [1] 17 and [1] 1.85. The [1] only numbers the first value printed. The two answers say different things about the plant: it grew 17 mm, and its final length is 1.85 times its initial length. The ratio has no unit, because mm divided by mm cancels. Both calculations are correct; which one you want depends on your question.

A script that remembers the calculation

Choose File → New File → R Script and save it as day06.R in the project folder. Write these lines in the script:

# Measurements are lengths in millimetres.
initial_mm <- 20
final_mm <- 37
growth_mm <- final_mm - initial_mm
growth_mm

Put the cursor on the first line and click Run (or press Ctrl+Enter, or Cmd+Enter on a Mac) to run it, then run each following line the same way. <- stores the value on its right under the name on its left, so read growth_mm <- final_mm - initial_mm as “store final minus initial under the name growth_mm”. The names appear in the Environment pane, and the last line prints 17. A line starting with # is a comment for people; R skips it.

Names must be typed exactly: growth_mm and Growth_mm are different names. Saving the script and running it are separate actions. Saving writes the instructions to disk; running creates the objects in R’s memory. That is why the script is what you keep: the objects disappear when R stops, and the script makes them again.

Three plants at once

c() combines several values into a vector, so one name can hold the lengths of three plants. Replace the single values in your script with:

initial_mm <- c(20, 22, 19)
final_mm <- c(37, 40, 34)
growth_mm <- final_mm - initial_mm
growth_mm
mean(growth_mm)
length(growth_mm)

R subtracts position by position, so the plants grew 17, 18 and 15 mm. mean() and length() are functions: a name followed by brackets, with the values to work on inside. The mean growth is about 16.67 mm, and length() counts 3 plants. The subtraction only makes sense because both vectors list the same three plants in the same order.

Use a comparison to find out which plants grew more than 16 mm:

growth_mm > 16

The answer, TRUE TRUE FALSE, says that the first two plants did and the third did not. Plant labels are text and go in quotes, plant_id <- c("P01", "P02", "P03"); "20" in quotes is text too, not a number. To read about a function, type ?mean in the Console and look at the Description and Examples.

How much did four plants grow?

Continue in day06.R. Write a comment above each part saying what it calculates and in which unit.

  1. A fourth plant grew from 21 to 39 mm. Add it to both vectors and use length() to check that each now has 4 values. The growth values are 17, 18, 15 and 18 mm, with a mean of 17 mm.
  2. Use division to find out how many times longer each plant became, and store the result as length_ratio. The values are about 1.85, 1.82, 1.79 and 1.86. Plants 2 and 4 both grew 18 mm, but plant 2 has the smaller ratio because it started longer (22 mm against 21 mm). If you prefer chemistry, do the product-yield calculation below instead.
  3. The first plant was re-measured: its final length is 38 mm, not 37. Predict which growth value changes, then edit the script and run it from the top. The first growth value becomes 18; the others stay the same.
  4. Find out whether your script is complete: save it, choose Session → Restart R, and run all lines from the top. You should get the same results, because everything the calculation needs is in the script.

Alternative: how much product was collected?

In a chemical synthesis, starting materials are turned into a product. For this simulated example the largest possible product mass is given: 1.00 g, stored as theoretical_mass_g. The dry product collected weighs 0.62 g, stored as isolated_mass_g; assume it is pure. The percentage yield is the collected mass as a percentage of the largest possible mass:

theoretical_mass_g <- 1.00
isolated_mass_g <- 0.62
yield_percent <- 100 * isolated_mass_g / theoretical_mass_g
yield_percent

The yield is 62%; the gram units cancel. Change the collected mass to 0.70 g and run the lines again to find out the new yield: 70%.

Error: object 'growth_mm' not found means R has no object with that name yet. Check the spelling and capitals, then run the line that creates it. A line in the editor does nothing until you run it. If the Console shows + instead of >, R is waiting for the end of a line: check quotes and brackets, or press Esc.

When a stored result goes stale

In a spreadsheet, a cell with a formula updates itself when its inputs change. An R object does not. Create a new script, day06-extended.R, to see what that means and why the order of plants matters.

  1. Write initial_mm <- 20, final_mm <- 37 and growth_mm <- final_mm - initial_mm, and run them. Then set final_mm <- 39 and print growth_mm without rerunning the subtraction. It still says 17, because growth_mm holds a number, not a formula. Rerun the subtraction and it says 19. Add a comment explaining this.
  2. Recreate the three-plant vectors from above. Suppose the final lengths had been typed in a different order, c(34, 37, 40). Store them as final_wrong and use final_wrong - initial_mm to find out what growth R reports: 14, 15 and 21 mm instead of 17, 18 and 15. R gives no warning, because both vectors still have three values; only you know which plant each position belongs to.
  3. Use division by 10 to convert the correct growth from mm to cm, and store it as growth_cm. Compare mean(growth_mm) and mean(growth_cm): 16.67 mm and 1.667 cm, the same growth in different units. Keep the original vector; give the converted one its own name.

If one vector is shorter than the other, R may reuse its values to fill the gap and give a result of the wrong length, sometimes with only a warning. Check both lengths with length() before subtracting.

How concentrated is the solution?

The same habit, every input named with its unit, works for laboratory calculations. A solution is a substance dissolved in a liquid. A mole (mol) is a unit of amount of substance, and the molar mass says how many grams one mole weighs (g/mol). The concentration in mol/L is the amount of substance divided by the final volume of solution in litres. All the values below are supplied.

Add this to day06-extended.R to find out the concentration of 0.2922 g sodium chloride (molar mass 58.44 g/mol) in a final volume of 100 mL:

mass_g <- 0.2922
molar_mass_g_mol <- 58.44
final_volume_ml <- 100
amount_mol <- mass_g / molar_mass_g_mol
final_volume_l <- final_volume_ml / 1000
concentration_mmol_l <- 1000 * amount_mol / final_volume_l
concentration_mmol_l

The amount is 0.005 mol in 0.100 L, so the concentration is 50 mmol/L (1 mmol is one thousandth of a mol). Keeping each step separate lets you check each conversion on its own.

  1. Predict what happens if you double the mass to 0.5844 g, then check: the concentration doubles to 100 mmol/L.
  2. Restore the mass and double the final volume to 200 mL instead. The same amount is now spread over twice the volume, so the concentration halves to 25 mmol/L.
  3. Use the same lines to find out the concentration of 0.9008 g glucose (molar mass 180.16 g/mol) in 100 mL. It is also 50 mmol/L: a glucose molecule is heavier, so the same number of moles weighs more.
  4. Save reports/calculation-check.txt with the formula in words, the conversion factors you used, and your three results. Then restart R and check that day06-extended.R reproduces them.

Check your understanding

The saved script. Objects live in R’s memory and disappear when R restarts; run the script again to recreate them.

Plant IDs are labels that name plants, not measurements. An average label has no meaning: R returns NA with a warning.

They must have the same length and list the same plants in the same order.

Keep: day06.R, with the four-plant example and comments about units. Next: import a whole table.