rmarkdown::render("report.Rmd", output_dir = "reports")Day 9 — Make a report that runs its own calculations
Lecture slides · Quiz · Weekly revision
Today’s question
You have code that calculates growth and draws a figure. How do you hand that to someone as a readable report, without copying numbers and pictures into a Word file by hand, where they go out of date as soon as the data change? An R Markdown report is one file, ending in .Rmd, that holds your text and your R code. Rendering it runs the code and produces an HTML page with the text, the results and the figures together. When the data change, you render again.
(These course webpages are made with Quarto, a close relative. You only need R Markdown.)
Save today: report.Rmd and its rendered HTML.
The report template
Open the project and click report.Rmd in the Files pane. Keep it in the project folder, next to data/, so that data/seedlings.csv still points to the data; moved into reports/, the same path would point to a folder that does not exist.
A minimal report looks like this:
---
title: "Seedling growth"
output: html_document
---
## Question
How much did the seedlings grow during the observation period?
```{r import}
library(readr)
library(dplyr)
seedlings <- read_csv("data/seedlings.csv", show_col_types = FALSE)
seedlings <- mutate(seedlings, growth_mm = final_mm - initial_mm)
```
There are `r nrow(seedlings)` plants in the dataset.
```{r mean-growth}
mean(seedlings$growth_mm)
```
Growth is final minus initial length, measured in millimetres.
It has three kinds of content. The header, between the two --- lines, sets the title and says the output is an HTML page. Ordinary text is written as is; ## Question makes a heading. A code chunk starts with three backticks and {r} and ends with three backticks; the word after r, such as import, is the chunk’s label, and every label must be different. The sentence with `r nrow(seedlings)` is inline code: when the report is rendered, R replaces it with the number of plants, 24.
A # means different things in the two places: in the text it makes a heading, inside a chunk it starts an R comment.
Rendering the report
Save the file and click Knit. R starts a fresh session, runs the chunks from top to bottom, and writes an HTML page that opens in a viewer. You can do the same from the Console:
rmarkdown::render uses the render() function from the rmarkdown package. output_dir = "reports" puts the HTML in reports/; the .Rmd stays where it is. Knit may put the HTML next to the .Rmd instead, so look for the file rather than assuming where it went. Never put the render line inside the report itself: the report would try to render itself.
Because rendering starts fresh, the report must contain every step it needs: library() lines, the import and the calculations. Something you only typed in the Console does not exist when the report is rendered.
A figure with a caption
Load ggplot2 in the first chunk, and add the growth plot from day 8 in its own chunk. fig.cap gives the figure a caption:
```{r growth-figure, fig.cap="Each point is one independently potted seedling."}
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)")
```
The caption says what the figure shows. Below it, write a sentence saying what you see, for example that growth varies within both groups and the groups overlap.
Your first report
- Render the supplied template before changing anything, to find out whether your setup works. An HTML page should open. If it does not, fix that first.
- Change the title and the question to your own words and render again.
- Put the import, the growth calculation and the labelled growth figure in chunks, in that order. If the template creates the same object twice, keep one.
- Write a short methods paragraph: what one row is (one plant), how growth was calculated, and in which unit.
- Misspell a column name on purpose, e.g.
growth_m, and render. Find the chunk label in the error message, fix the spelling, and render again. - Restart R (Session → Restart R) and render once more. It works, because the report contains every step it needs.
Read the first error and the chunk label it names. Is the package loaded with library() before its functions are used? Are the data imported before the calculation? Are the file and column names spelt exactly? Does every chunk have an opening and a closing fence? When you ask for help, include the error text.
When rendering stops
Errors are easier to fix once you have seen them on purpose. Save a copy of your report as report-workshop.Rmd, in the project folder, and break it in three ways, one at a time. Each time, note in reports/render-recovery.txt what you changed, the first line of the error, and how you fixed it; then fix it and render again before the next break.
- Give two chunks the same label to find out what R says. It stops with a message about a duplicate chunk label and names the label.
- Misspell the CSV file name in the import, e.g.
data/seedling.csv, to find out what a missing input looks like. The error says the file does not exist. An object of the same name left in your Console does not help, because rendering starts fresh. - Move the plot chunk above the chunk that calculates
growth_mm. The error saysgrowth_mm(orseedlings) was not found: chunks run from top to bottom, so a figure can only use what earlier chunks made.
Finally, open the HTML in a browser next to the .Rmd. The .Rmd is the recipe you edit; the HTML is the reading copy, and changes made to it are lost at the next render. The measurements themselves are in data/seedlings.csv.
A report for the second class’s data
Use Save As to make transfer-report.Rmd, in the project folder, for the 18-plant study in data/seedlings-transfer.csv. The point is a report that describes that study and nothing else.
- Change the import to
data/seedlings-transfer.csvand call the tabletransfer. Keep thelibrary()lines and the growth calculation in the report. - Use inline code to state the number of plants, so the report itself finds out how many there are. The HTML should say 18.
- Rewrite the question, methods and caption for this study: 18 plants, 9 per group. Add the growth-by-group figure and the initial-versus-final figure from
day08-transfer.R, each with a caption saying what one point is and what the y-axis measures. - Restart R and render. Then search the
.Rmdfor24and forseedlings.csv. Every hit is a sentence or line that may still describe the other study; fix any that do. - Find out whether the report works in another place: copy
transfer-report.Rmd,introcomputing.Rproj, thedatafolder and emptyoutputandreportsfolders into a new practice folder, open that copy’s.Rprojand render there. If something is missing, note it inrender-recovery.txt.
The finished transfer report describes 18 plants, 9 per group, none missing, and T01 grew 15.0 mm.
A number typed into the text does not change when the data change. Replace it with inline code such as `r nrow(transfer)`, and check that the import really reads the transfer file.
Check your understanding
The .Rmd source, its input data and the HTML. The HTML is convenient to read, but only the .Rmd can make it again.
A typed number stays the same when the data change. Inline code recalculates it at every render.
Keep: your saved report.Rmd and a successfully rendered HTML report. Next: write your first complete short report.