Skip to main content

Capstone Exercise

Putting it all together: an optional exercise to do after the course

Author

Jean Golding Institute

Can I build a project, from scratch, that someone else could run?

This is an exercise to do after the course, on your own. It uses every section of the course: you build a tidy project, give it an environment, and write a report with code in it, laid out like a short paper. At the end, you test it the way a colleague would.

It takes about an hour or two. Do it in R or in Python: where the steps differ, there is a tab for each. You need:

What you will build

File or folder What it is
penguin-project/
├── README.md What the project is, and how to run it
├── _quarto.yml Report settings: puts the report in outputs/
├── report.qmd The report
├── references.bib The reference list
├── data/
│ ├── raw/penguins.csv The original data: never edited
│ └── processed/
│ ├── penguins_clean.csv The cleaned data, made by the cleaning script
│ └── penguins_clean_dictionary.csv Explains each column (you write this)
├── code/01_clean_data.R Cleans the data (01_clean_data.py in Python)
├── outputs/ The rendered report (HTML, PDF and Word)
├── renv.lock The lock file, which records the environment (uv.lock in Python)
└── renv/ The environment itself: disposable (.venv/ in Python)

In Python, uv also makes pyproject.toml and .python-version, which describe the project and its Python version. Keep them with the lock file.

Step 1: A tidy project

Make a new folder called penguin-project, somewhere outside the example folder. Inside it, make the folders data/raw, data/processed, code and outputs.

Copy tidy-project/data/raw/penguins.csv from the example folder into data/raw/. This is your raw data: from now on, you never edit it.

Start a README.md. You’ll finish it in step 5, but write down what the project is now:

README.md
# Penguin body mass

Does body mass differ between male and female Gentoo penguins?
**Status:** in progress.

## Data

Penguin measurements from near Palmer Station, Antarctica
(Gorman, Williams and Fraser, 2014).

Step 2: An environment

Open a terminal (or, for R, RStudio or Positron) in the penguin-project folder, and give the project its own environment.

In RStudio, make the folder a project first: File → New Project → Existing Directory. In Positron, open the folder. Then run these in the R console:

renv::init()                                 # give this project its own environment
install.packages(c("knitr", "rmarkdown"))    # Quarto needs these to run R code

renv::init() makes the lock file, renv.lock, and a renv/ folder, which holds the environment. From now on, the packages you install in this project go into its own environment, and don’t affect your other projects. You’ll record them in the lock file in step 5.

Terminal/Command Prompt
uv init --no-package
uv add pandas matplotlib jupyter tabulate

uv init makes pyproject.toml and .python-version, and a starter main.py, which you can delete. uv add makes the environment (the .venv folder), installs the packages into it, and records them in the lock file, uv.lock. pandas and matplotlib are for the analysis. Quarto needs jupyter to run Python code, and tabulate helps it make tables.

--no-package keeps the project simple: without it, newer versions of uv set the project up as a Python package to share, which this project doesn’t need.

Step 3: Clean the data

Write a script that reads the raw data, removes the incomplete rows, and saves a clean copy in data/processed/. The raw file is never changed.

code/01_clean_data.R
# Reads the raw data, removes incomplete rows, and saves a clean copy.
# Run from the project folder: Rscript code/01_clean_data.R

raw <- read.csv("data/raw/penguins.csv")
clean <- na.omit(raw)
write.csv(clean, "data/processed/penguins_clean.csv", row.names = FALSE)

Run it:

Terminal/Command Prompt
Rscript code/01_clean_data.R

Or open the script in RStudio or Positron, and press Source.

code/01_clean_data.py
"""Reads the raw data, removes incomplete rows, and saves a clean copy.

Run from the project folder: uv run code/01_clean_data.py
"""
import pandas as pd

raw = pd.read_csv("data/raw/penguins.csv")
clean = raw.dropna()
clean.to_csv("data/processed/penguins_clean.csv", index=False)

Run it inside the environment:

Terminal/Command Prompt
uv run code/01_clean_data.py

Then write a data dictionary for the clean data, data/processed/penguins_clean_dictionary.csv, with one row per column: its name, type, description and units. Look at the first rows of the data to work them out. If you get stuck, compare yours with the one in tidy-project/data/processed/.

Step 4: Write the report

Make a file called _quarto.yml in the project folder, so that everything Quarto makes goes in outputs/:

_quarto.yml
project:
  output-dir: outputs

Then make report.qmd, and build it up one part at a time. Render after each part to see what changed:

Press Render in RStudio or Positron, or run this in a terminal. Quarto uses the project’s environment by itself.

Terminal/Command Prompt
quarto render report.qmd

Render it with uv run, so that Quarto uses the project’s environment:

Terminal/Command Prompt
uv run quarto render report.qmd

4a. A header like a paper’s

As well as the title, add a date, an abstract, numbered sections and a table of contents. echo: false hides the code, so readers see only the results. The code is still in the file.

report.qmd
---
title: "Body mass of Gentoo penguins"
author: "Your name here"
date: today
abstract: |
  Male Gentoo penguins are heavier than females. This report
  measures the difference.
number-sections: true
execute:
  echo: false
format:
  html:
    toc: true
    embed-resources: true
  typst: default
  docx: default
---

4b. Read the data

Under the header, add a chunk that reads the clean data and keeps one species, and a sentence with inline code, so the number updates when the data changes:

report.qmd
```{r}
clean <- read.csv("data/processed/penguins_clean.csv")
gentoo <- subset(clean, species == "Gentoo")
by_sex <- aggregate(body_mass ~ sex, data = gentoo, FUN = mean)
```

## Data

After removing incomplete rows, there are `{r} nrow(gentoo)` Gentoo
penguins in the data.
report.qmd
```{python}
import matplotlib.pyplot as plt
import pandas as pd
from IPython.display import Markdown

clean = pd.read_csv("data/processed/penguins_clean.csv")
gentoo = clean[clean["species"] == "Gentoo"]
by_sex = gentoo.groupby("sex")["body_mass"].mean().round()
```

## Data

After removing incomplete rows, there are `{python} len(gentoo)` Gentoo
penguins in the data.

4c. A table, with a caption

Add a ## Results heading, then a chunk whose label starts with tbl-. Quarto numbers it as a table:

report.qmd
```{r}
#| label: tbl-sex
#| tbl-cap: "Mean body mass of Gentoo penguins, by sex"
knitr::kable(by_sex, col.names = c("Sex", "Mean body mass (g)"), digits = 0)
```
report.qmd
```{python}
#| label: tbl-sex
#| tbl-cap: "Mean body mass of Gentoo penguins, by sex"
table = by_sex.reset_index()
table.columns = ["Sex", "Mean body mass (g)"]
Markdown(table.to_markdown(index=False))
```

4d. A figure, with a caption

In the same way, a label starting with fig- makes a numbered figure. fig-alt describes it for people who use a screen reader:

report.qmd
```{r}
#| label: fig-mass
#| fig-cap: "Body mass of Gentoo penguins, by sex"
#| fig-alt: "Boxplot of Gentoo body mass: males are heavier than females"
boxplot(body_mass ~ sex, data = gentoo, xlab = "Sex", ylab = "Body mass (g)")
```
report.qmd
```{python}
#| label: fig-mass
#| fig-cap: "Body mass of Gentoo penguins, by sex"
#| fig-alt: "Boxplot of Gentoo body mass: males are heavier than females"
ax = gentoo.boxplot(column="body_mass", by="sex", grid=False)
ax.set_title("")
plt.suptitle("")
ax.set_xlabel("Sex")
ax.set_ylabel("Body mass (g)")
plt.show()
```

4e. Refer to them

Write @tbl-sex or @fig-mass in the text, and Quarto replaces it with “Table 1” or “Figure 1”, with a link. The numbers stay right if you add more tables or figures. Put the result in a sentence too, with inline code:

report.qmd
On average, males were `{r} round(diff(by_sex$body_mass))` g heavier
than females (@tbl-sex and @fig-mass).
report.qmd
On average, males were `{python} int(by_sex["male"] - by_sex["female"])` g heavier
than females (@tbl-sex and @fig-mass).

4f. Cite a source

Make a file called references.bib, with two sources: the paper the data comes from, and the palmerpenguins package that shares it. Each entry starts with a citation key (here gorman2014 and palmerpenguins), which is the name you use to cite it. Reference managers such as Zotero can export .bib files for you.

references.bib
@article{gorman2014,
  title   = {Ecological Sexual Dimorphism and Environmental Variability
             within a Community of {Antarctic} Penguins (Genus {Pygoscelis})},
  author  = {Gorman, Kristen B. and Williams, Tony D. and Fraser, William R.},
  journal = {PLoS ONE},
  year    = {2014},
  volume  = {9},
  number  = {3},
  pages   = {e90081},
  doi     = {10.1371/journal.pone.0090081}
}

@manual{palmerpenguins,
  title   = {palmerpenguins: Palmer Archipelago (Antarctica) Penguin Data},
  author  = {Horst, Allison Marie and Hill, Alison Presmanes and Gorman, Kristen B.},
  year    = {2020},
  note    = {R package version 0.1.0},
  doi     = {10.5281/zenodo.3960218},
  url     = {https://allisonhorst.github.io/palmerpenguins/}
}

Add bibliography: references.bib to the header. Add an ## Introduction that cites both sources by their keys, with [@gorman2014] and [@palmerpenguins], and a ## References heading at the end. Quarto formats each citation, and adds the reference list under that heading.

4g. Render all the formats

Open the HTML, PDF and Word versions in outputs/. The section numbers, captions, cross-references and citations are in all three, from one file. You should find 119 Gentoo penguins, with males about 805 g heavier than females.

Step 5: Record it

Record the packages in the lock file, and finish the README.

renv::snapshot()

renv looks through the project’s code for the packages it uses, and records them, at the versions installed, in renv.lock.

There is nothing to do: uv add already recorded the packages in uv.lock.

Now finish the README, so that someone else can run the project. Add a Quickstart (what to run, in order), a Setup (the software and versions it needs, including the version of R or Python) and the Contents (what is in each folder). Use tidy-project/README.md as a model. Change the status to complete.

Step 6: The new laptop test

Now test your project the way a colleague would, on a computer that has never seen it. Delete everything that can be re-made: the environment, data/processed/penguins_clean.csv and the outputs/ folder. Then follow your own README to rebuild it:

Delete the renv/library folder, then restart R. Rebuild the environment from the lock file, then run the project:

renv::restore()
Terminal/Command Prompt
Rscript code/01_clean_data.R
quarto render report.qmd

Delete the .venv folder. (It’s a hidden folder, so you may need to show hidden files to see it.) Then rebuild the environment from the lock file, and run the project:

Terminal/Command Prompt
uv sync
uv run code/01_clean_data.py
uv run quarto render report.qmd

Do you get the same report, with the same numbers? If anything was missing from your README, add it. For a real test, zip the project (without the environment) and send it to a colleague: can they run it from the README alone?

To compare your project with a finished one, open capstone-answer/ in the example folder. It has the whole project in R (r/) and in Python (python/), with the lock file and the rendered report in outputs/. The main files are below too.

report.qmd
---
title: "Body mass of Gentoo penguins"
author: "Your name here"
date: today
abstract: |
  Male Gentoo penguins are heavier than females. This report
  measures the difference.
number-sections: true
execute:
  echo: false
bibliography: references.bib
format:
  html:
    toc: true
    embed-resources: true
  typst: default
  docx: default
---

```{r}
clean <- read.csv("data/processed/penguins_clean.csv")
gentoo <- subset(clean, species == "Gentoo")
by_sex <- aggregate(body_mass ~ sex, data = gentoo, FUN = mean)
```

## Introduction

Penguins near Palmer Station, Antarctica, were measured between
2007 and 2009 [@gorman2014]. We use the version of the data in
the palmerpenguins package [@palmerpenguins], and look at one
species, Gentoo.

## Data

After removing incomplete rows, there are `{r} nrow(gentoo)` Gentoo
penguins in the data.

## Results

On average, males were `{r} round(diff(by_sex$body_mass))` g heavier
than females (@tbl-sex and @fig-mass).

```{r}
#| label: tbl-sex
#| tbl-cap: "Mean body mass of Gentoo penguins, by sex"
knitr::kable(by_sex, col.names = c("Sex", "Mean body mass (g)"), digits = 0)
```

```{r}
#| label: fig-mass
#| fig-cap: "Body mass of Gentoo penguins, by sex"
#| fig-alt: "Boxplot of Gentoo body mass: males are heavier than females"
boxplot(body_mass ~ sex, data = gentoo, xlab = "Sex", ylab = "Body mass (g)")
```

## References
README.md
# Penguin body mass

Does body mass differ between male and female Gentoo penguins?
**Status:** complete.

## Quickstart

1. Open this folder in RStudio or Positron, and run `renv::restore()`
   in the R console to install the packages.
2. Run `Rscript code/01_clean_data.R` to make the clean data.
3. Run `quarto render report.qmd` to make the report, in `outputs/`.

## Setup

- R 4.3 or later. The packages are in `renv.lock`.
- Quarto 1.4 or later.

## Contents

- `data/raw/` the original data (never edited)
- `data/processed/` the clean data, made by `code/01_clean_data.R`,
  and `penguins_clean_dictionary.csv`, which explains each column
- `code/` the scripts
- `report.qmd` the report, and `references.bib` its references
- `_quarto.yml` settings for the report (it puts the results in `outputs/`)
- `outputs/` the rendered report. Safe to delete

## Data

Penguin measurements from near Palmer Station, Antarctica
(Gorman, Williams and Fraser, 2014).
report.qmd
---
title: "Body mass of Gentoo penguins"
author: "Your name here"
date: today
abstract: |
  Male Gentoo penguins are heavier than females. This report
  measures the difference.
number-sections: true
execute:
  echo: false
bibliography: references.bib
format:
  html:
    toc: true
    embed-resources: true
  typst: default
  docx: default
---

```{python}
import matplotlib.pyplot as plt
import pandas as pd
from IPython.display import Markdown

clean = pd.read_csv("data/processed/penguins_clean.csv")
gentoo = clean[clean["species"] == "Gentoo"]
by_sex = gentoo.groupby("sex")["body_mass"].mean().round()
```

## Introduction

Penguins near Palmer Station, Antarctica, were measured between
2007 and 2009 [@gorman2014]. We use the version of the data in
the palmerpenguins package [@palmerpenguins], and look at one
species, Gentoo.

## Data

After removing incomplete rows, there are `{python} len(gentoo)` Gentoo
penguins in the data.

## Results

On average, males were `{python} int(by_sex["male"] - by_sex["female"])` g heavier
than females (@tbl-sex and @fig-mass).

```{python}
#| label: tbl-sex
#| tbl-cap: "Mean body mass of Gentoo penguins, by sex"
table = by_sex.reset_index()
table.columns = ["Sex", "Mean body mass (g)"]
Markdown(table.to_markdown(index=False))
```

```{python}
#| label: fig-mass
#| fig-cap: "Body mass of Gentoo penguins, by sex"
#| fig-alt: "Boxplot of Gentoo body mass: males are heavier than females"
ax = gentoo.boxplot(column="body_mass", by="sex", grid=False)
ax.set_title("")
plt.suptitle("")
ax.set_xlabel("Sex")
ax.set_ylabel("Body mass (g)")
plt.show()
```

## References
README.md
# Penguin body mass

Does body mass differ between male and female Gentoo penguins?
**Status:** complete.

## Quickstart

1. Install [uv](https://docs.astral.sh/uv/), then run `uv sync` in this
   folder to install Python and the packages.
2. Run `uv run code/01_clean_data.py` to make the clean data.
3. Run `uv run quarto render report.qmd` to make the report, in `outputs/`.

## Setup

- Python 3.12 or later (uv installs it). The packages are in `uv.lock`.
- Quarto 1.4 or later.

## Contents

- `data/raw/` the original data (never edited)
- `data/processed/` the clean data, made by `code/01_clean_data.py`,
  and `penguins_clean_dictionary.csv`, which explains each column
- `code/` the scripts
- `report.qmd` the report, and `references.bib` its references
- `_quarto.yml` settings for the report (it puts the results in `outputs/`)
- `outputs/` the rendered report. Safe to delete

## Data

Penguin measurements from near Palmer Station, Antarctica
(Gorman, Williams and Fraser, 2014).

Going further: a full paper

Quarto can also make a whole journal article, called a manuscript, from one or more .qmd files or notebooks. It publishes the paper as a website, with the PDF, Word and JATS versions, and the code and notebooks behind each figure, side by side. Quarto’s tutorial works through an example paper, La Palma Earthquakes, which is a good model to copy for your own paper. There is a version for each way of working, and each has a template on GitHub that you can copy and render yourself:

Other ways to take it further:

  • Add a code/run_all.R (or .py) that rebuilds everything from the raw data in one go, like the one in tidy-project/.
  • Put the project in git, and on GitHub. We cover this in a separate git and GitHub course.
  • Share the data. See the Q-FAIR section of the notes.