cat("Hello!")Hello!
Jean Golding Institute
Welcome to this course! These notes go with the slides. You can use them afterwards to revisit the detail, and you can also work through them on your own: each section ends with a “Try it yourself” activity, with instructions and an answer you can open.
The course introduces practical habits that make your research easier to re-run, understand and share. The course contains examples for both Python and R, with opportunities to include your own code and examples.
By the end of this course you will be able to:
Small snippets of code are shown in a grey box like this:
When the code is run, its output is shown below it, marked with a vertical red line:
Larger pieces of code are shown as scripts with a filename:
Commands to run in a terminal look like this:
In each section there is a “Try it yourself” activity, which is also on the slides. Activities are shown in a box with a red top edge, and each one ends with a yellow box that contains the answer. Try each one yourself before looking at the answer.
An example activity
This is an exercise. Click the box below to see the answer.
This is the answer.
Important points are highlighted in green boxes like this one:
These are important concepts and technical notes.
The live activities don’t need you to write or run any code: the only thing you run is Render. You need two things.
Quarto. We use Quarto to build documents. RStudio and Positron include it, so if you use either you probably don’t need to install anything. To check, open a .qmd file and look for the Render button. Otherwise, install Quarto for your operating system (VS Code users also need the Quarto extension). Use version 1.4 or later: quarto --version in a terminal shows which you have.
The example folder. Download the example folder and unzip it. It has five folders, and the checklist:
| Folder | What it is |
|---|---|
messy-project/ |
A project with a bad structure and bad names |
tidy-project/ |
The same project with all the good habits |
one-document/ |
A short report to turn into HTML, PDF and Word |
environment-demo/ |
A small project in R (r/) and in Python (python/), for trying environments with renv or uv (optional) |
capstone-answer/ |
A finished answer to the capstone exercise, in R (r/) and in Python (python/) |
checklist.pdf, checklist.docx |
A one-page checklist for your own project |
If you want to do the optional capstone exercise, you will also need R or Python, and uv (Python) or the renv package (R).
How should I organise a project so that I, and others, can find things and re-run them?
About 25 min · Activity: Rescue the messy project
A project that has grown organically tends to look like a folder full of files called data.csv, data_final.csv, analysis2.R and analysis_NEW.py. This causes three problems:
Making a project more reproducible helps you first and others second:
Open messy-project/ in the example folder. It looks like this:
messy-project/
├── Copy of data.csv
├── analysis.R
├── analysis2 (copy).R
├── analysis_OLD.R
├── clean.R
├── data.csv
├── data_FINAL_USE_THIS.csv
├── data_final.csv
├── data_final_v2.csv
├── notes.txt
├── plot1.png
├── plot_new.png
├── report_draft.docx
├── results.xlsx
├── results_v3.xlsx
└── untitled.R
Questions to ask of this layout:
This happens naturally. You start by exploring a dataset in a notebook, a script or an Excel sheet. The analysis grows, then a second analysis is added, and it becomes hard to see how you got from the raw data to the results.
Now open tidy-project/. It holds the same project, organised:
| File or folder | What it is |
|---|---|
tidy-project/ |
|
├── README.md |
What the project is, and how to run it |
├── report.qmd |
The report |
├── _quarto.yml |
Report settings |
├── data/ |
|
│ ├── raw/penguins.csv |
The original data: never edited |
│ └── processed/ |
|
│ ├── penguins_clean.csv |
The cleaned data, made by the code |
│ └── penguins_clean_dictionary.csv |
Explains each column |
├── code/ |
|
│ ├── 01_clean_data.R |
Numbered, in the order to run them |
│ └── run_all.R |
Rebuilds everything |
└── outputs/ |
Made by the code: safe to delete |
The key ideas are:
raw data -> clean -> analyse -> results. Numbering the files shows the order to run them in.outputs/ and data/processed/ can be re-made by running the code. code/run_all.R does exactly that: delete them, run it, and they come back.Spreadsheets. The same structure works for spreadsheets:
data/raw folder and never edit it. Open it, then use Save As to put a working copy in data/processed.1_raw, 2_cleaned, 3_results) rather than leaving Sheet1.How much structure a project needs is a judgement call. A small one-off analysis may not need all of this. Aim for what is useful, not what is perfect.
Open messy-project/ in the example folder (you do not need to run anything).
| Files | What to do | |
|---|---|---|
| Raw data | data.csv |
Never edit it |
| Cleaned data | data_final.csv, data_final_v2.csv, data_FINAL_USE_THIS.csv |
Three versions of one thing, with no way to tell which is right. Make it from the raw data with code |
| Code | clean.R, analysis.R, analysis2 (copy).R, analysis_OLD.R, untitled.R |
One script per step, numbered. Delete the copies |
| Results | plot1.png, plot_new.png, results.xlsx, results_v3.xlsx |
The code can re-make these |
| Documents | notes.txt, report_draft.docx |
Become the README and the report |
| Delete | Copy of data.csv |
A duplicate |
Compare your answer with tidy-project/. To see the “everything can be re-made” idea for yourself, look at tidy-project/code/run_all.R: it deletes the cleaned data and the report, then makes them again from the raw data.
How do I explain my project, and report on it, so others (and future me) can use it?
About 45 min · Demo · Activities: be the new colleague; one document, many formats
| Type | Where | Why | Audience |
|---|---|---|---|
| Comments in code | Scripts, notebooks, function docstrings | Explain or justify what isn’t obvious from the code | Other researchers and developers |
| Files in the repository | README.md |
Describe how to use the project | Developers, and people running the code |
| Data dictionary | A CSV next to the data | Explain what each column means, its units and missing values | Anyone using the data |
| External documentation | A website or report | Describe what you are doing in less technical terms, with quickstart guides | Users and less technical readers |
A good comment says why, not what. # remove outliers > 3 SD, as agreed with the lab is more useful than # remove outliers.
A README is a plain text file in the top folder of the project. It is the first thing someone reads, and it helps you in six months’ time as much as it helps anyone else. It should contain:
Here is the README from tidy-project/. It is written in Markdown, which is a simple way of marking up text:
# Penguin body mass analysis
Body measurements of 333 penguins on three islands. **Status:** complete.
## Quickstart
1. Open this folder in RStudio or Positron (or a terminal).
2. Run `code/run_all.R`. It cleans the data and builds the report in `outputs/`.
## Setup
- R 4.3 or later (no extra packages needed)
- Quarto 1.4 or later (to make the report)
## Contents
- `data/raw/` the original data (never edited)
- `data/processed/` the cleaned data, and a data dictionary explaining each column
- `code/` the scripts
- `report.qmd` the report, which makes HTML, PDF and Word versions
- `_quarto.yml` settings for the report (it puts the results in `outputs/`)
- `outputs/` made by `run_all.R`. Safe to deleteYou can use a README in any project, whether or not you write code. For a spreadsheet project it is the place to record what each sheet does and how the data was collected.
A dataset on its own doesn’t explain itself. What does bill_dep mean? Is body_mass in grams or kilograms? Does a blank mean it wasn’t measured? Write this down in a data dictionary, a small table with one row per column:
| column | type | description | units / values |
|---|---|---|---|
species |
text | Penguin species | Adelie, Chinstrap, Gentoo |
island |
text | Island where the penguin was observed | Biscoe, Dream, Torgersen |
bill_len |
number | Bill length | mm |
bill_dep |
number | Bill depth | mm |
flipper_len |
number | Flipper length | mm |
body_mass |
number | Body mass | grams |
sex |
text | Sex of the penguin | female, male |
year |
number | Year of the study | 2007, 2008 or 2009 |
Save it next to the data (for example data/processed/penguins_clean_dictionary.csv) and refer to it from your README. You can also include a short description of the whole dataset: who collected it, when, how, and any known problems. A dictionary is one of the most valuable things you can write, because only the person who knows the data can.
To make one, copy your column names into a spreadsheet or CSV file, then add columns for the type, a description, and the units or values. Fill them in by hand, and save the file as a CSV next to the data.
Quarto is a free, open-source tool for writing documents that combine text and code. You write one file (report.qmd). When you render it, the code runs, and the results (numbers, tables and figures) are put into a finished document, such as an HTML page, a PDF or a Word file.
Quarto works with R, Python and other languages, from the IDE you already use. The slides, the notes and the website for this course are all made with Quarto.
A report is often the last step of an analysis, and the easiest place to introduce mistakes: a number is copied from the wrong run, or a figure is from an older version of the data. Quarto removes that step.
.qmd file is easy to share, compare and keep in version control, in any editor.| Without Quarto | With Quarto | |
|---|---|---|
| 1 | Run the analysis | Write the report once, with the code in it |
| 2 | Copy numbers and plots into a Word document | Render |
| 3 | The data changes | The data changes |
| 4 | Repeat by hand, and hope you caught every number | Render again |
A Quarto file has four ingredients:
---).report.qmd
---
title: "Penguin report"
format: html
---
## Data
```{r}
clean <- read.csv("data/processed/penguins_clean.csv")
# keep one species: filter out Adelie and Chinstrap
gentoo <- subset(clean, species == "Gentoo")
```
After removing incomplete rows, there are `{r} nrow(clean)` penguins in the data. `{r} nrow(gentoo)` of them are Gentoo penguins.
## Results
The mean body mass of Gentoo penguins was `{r} round(mean(gentoo$body_mass))` g.
```{r}
boxplot(body_mass ~ sex, data = gentoo, ylab = "Body mass (g)")
```report.qmd
---
title: "Penguin report"
format: html
---
## Data
```{python}
import pandas as pd
clean = pd.read_csv("data/processed/penguins_clean.csv")
# keep one species: filter out Adelie and Chinstrap
gentoo = clean[clean["species"] == "Gentoo"]
```
After removing incomplete rows, there are `{python} len(clean)` penguins in the data. `{python} len(gentoo)` of them are Gentoo penguins.
## Results
The mean body mass of Gentoo penguins was `{python} round(gentoo["body_mass"].mean())` g.
```{python}
gentoo.boxplot(column="body_mass", by="sex")
```(The plot needs the matplotlib package.)
Quarto can be used for the written part of a project even if your analysis is in a spreadsheet. Save your final table as a CSV, then include it in the report:
report.qmd
This still needs R installed. If you’d rather not use code at all, a README and clearly labelled sheets are the best documentation you can write.
Because the numbers in the report come from code, a change in the data flows through to the report:
new data -> re-run the cleaning script -> render the report -> updated report
Every number, table and figure is recalculated, and sentences with inline code update too. There is nothing to copy and paste. This is the main reason to use Quarto for reproducible research: change the data (or the code), not the report.
One of the best things about Quarto is that one source file can make several kinds of document. You list the formats you want in the header:
format:
html: default
typst: default
docx: default
html makes a web page.typst makes a PDF. Typst comes with Quarto, so you don’t need to install LaTeX.docx makes a Word document.When you render, Quarto makes all three from the same text, code and figures. Change the title, a sentence or the data once, and every format changes.
To render, press the Render button in your IDE (use the format menu to choose which one), or run this in a terminal to make every format at once:
@fig-mass and Quarto writes “Figure 1”, with a link, and keeps the numbers right as you add or move figures. The capstone exercise shows how.The activities in this course don’t need any code. If you want to write a Quarto report with code in it, with numbered sections, a table, a figure, cross-references and a citation, the capstone exercise takes you through it, in R or Python.
You have inherited the messy project. Open messy-project/notes.txt: it is the only documentation. Look at the first rows of messy-project/data.csv too.
tidy-project/README.md and tidy-project/data/processed/penguins_clean_dictionary.csv. Which of your three things do they answer?Typical things you can’t work out from the messy project: how to run it and in what order (the notes say “i think”); which software and versions it needs; what bill_dep means and whether body_mass is in grams or kilograms; which data file is the real one; which figure is which.
The README answers how to run it, what software it needs and what is where. The data dictionary answers what each column means, with its type and units. A good README answers three questions in the first minute: What is this project and is it finished? If I just want to run it, what do I do first? What do I need installed?
You need Quarto, but not R or Python.
one-document/report.qmd.quarto render report.qmd to make all three.If Render doesn’t work, open the ready-made files in one-document/finished/.
Your changes appeared in every format, because there is only one source. That is the point: you never copy and paste between a web page, a PDF and a Word file.
If only one format appeared, Render was set to a single format. Use the format menu, or the quarto render report.qmd command, to make all three.
How do I make sure my code still runs next month, or on someone else’s computer?
About 30 min · Demo · Activity: The new laptop test
Imagine this sequence:
tidyr).| Old project | New project | |
|---|---|---|
| Program | R 4.3.0 | R 4.3.0 |
tidyr |
1.2.1 | 1.3.1 |
ggplot2 |
3.3.5 | 3.5.0 |
Your computer has one shared set of packages, so two projects that need different versions can’t both be happy. This happens for several reasons:
An environment is a project’s own set of packages, at the versions it needs. Instead of one shared library for every project, each project has its own, so projects can’t interfere with each other.
Environments work with two things:
The environment is disposable: you can delete it, and rebuild it from the lock file whenever you like. The lock file is the thing you keep.
| Tool | uv |
renv |
conda |
pixi |
|---|---|---|---|---|
| Works with | Python | R | Python, R and other software | Python, R and other software |
| Lock file (keep it) | uv.lock |
renv.lock |
environment.yml* |
pixi.lock |
| Environment (disposable) | .venv |
renv/library |
Kept by conda, outside your project | .pixi |
| Rebuild it | uv sync |
renv::restore() |
conda env create -f environment.yml |
pixi install |
uv and renv each work with one language. conda and pixi can install Python, R, and other software that isn’t a package for either (such as GDAL or a C library), which helps if a project mixes languages. pixi is the newer of the two, and works like uv: it keeps the environment in the project folder and writes a lock file for you.
* environment.yml lists the packages, but not always their exact versions, so it isn’t a true lock file. Make it with conda env export > environment.yml, or use conda-lock for a full lock file.
Other tools do the same job, such as Python’s built-in venv with a requirements.txt file. The idea is the same whichever you use: a file that records what the project needs.
You don’t need to run this in the course. It shows what using an environment looks like, so you can try it on a project of your own. There are only two steps to remember: make the environment once, and rebuild it from the lock file whenever you need to. The example folder has a small project in each language to practise on, environment-demo/r/ and environment-demo/python/, with the steps in their READMEs.
This is the payoff. Because the lock file records exactly what the project needs, you can send your project to a colleague, a reviewer, or yourself on a new laptop, and they can rebuild the same environment with one command:
your project + lock file -> colleague rebuilds the environment -> same packages, same results
uv can pin the Python version; renv records the R version but doesn’t install it.)That is good enough for almost every project. Perfect is not the goal.
There are no packages to install, but the software version can still matter: formulas and functions differ between Excel versions, and add-ins vary. Write the program and its version in your README (for example Excel for Microsoft 365, version 2410), along with any add-ins used. The next person then knows what you used, which is the same idea.
The live session doesn’t need you to run any commands. If you want to try environments yourself:
environment-demo/r/ (R, with renv) or environment-demo/python/ (Python, with uv) from the example folder and follow the steps in its README.md: you set up an environment, delete it, and rebuild it from the lock file.renv) or Python (with uv), work through the capstone exercise.venv and conda.A colleague emails you their project: “It runs fine on my laptop!” You open it on your own laptop, and it says there is no package called ggplot2.
On your own, list everything you would need to know to run this project on a new computer. Write down as many things as you can.
| You need to know | Where it should be written down |
|---|---|
| Which software, and which version | The README (Setup) |
| Which packages, and which versions | A lock file |
| Where the data is | The README, and a data/raw folder |
| What to run, and in what order | The README (Quickstart), or one script |
| Where the results come from | The code, not copy and paste |
Almost all of this can be written down once, in a README. A lock file records the packages for you. Look at tidy-project/README.md: it answers most of these.
What will you do differently on Monday?
About 15 min · Activity: Your checklist
This whole course is one journey:
Messy -> Tidy -> Documented -> Reported -> Recorded -> Shareable
Each step is a habit, and you can start with any of them.
Tick what your own project already does. There is a one-page version to print or edit in the example folder (checklist.pdf and checklist.docx).
| Structure | ☐ My raw data is never edited ☐ Raw data, cleaned data, code and results are kept in separate places ☐ My files have clear names ☐ I could re-make my results from the raw data |
| Documentation | ☐ There is a README ☐ My columns are explained in a data dictionary ☐ My report is made from the data and code |
| Environments | ☐ I have written down which software and versions I used ☐ My packages are recorded in a file ☐ A colleague could run my project on a new computer |
| Sharing | ☐ My data is in an open format such as CSV ☐ I know where I would share it, and under which licence ☐ Someone else could find, understand and reuse it |
Some steps give a lot of benefit for very little effort:
| Quick win | Time | Why it helps |
|---|---|---|
| Stop editing the raw data | 0 min | Everything can be re-made |
| Clear folders and file names | 15 min | You can find things |
| Write a README | 15 min | Others, and future you, can run it |
| Write down your software versions | 5 min | It runs on another computer |
| Describe your columns | 20 min | Your data makes sense to others |
messy-project/ if you don’t have one).There is no single right answer, but a good first step is small and quick. If you can’t decide, start with the first thing in the quick wins table that you haven’t done yet. A README is a very good first step: it takes 15 minutes, and it helps everyone, including future you.
Getting the balance right is hard: do what you can. You learn by doing, so try to put one or two of these ideas into your next project.
How do I know my data is good enough to share, and how do I share it?
Optional extra · Activity: Q-FAIR detective
This section is optional in the live course, but it is written in full so you can work through it on your own.
The FAIR principles are a well-known checklist for sharing data. Q-FAIR adds Quality at the start:
| Letter | Principle | What it means in practice | Where we met it |
|---|---|---|---|
| Q | Data Quality | Data is accurate, complete and documented. You know where it came from and what was done to it. | Raw data is never overwritten; the pipeline records every change. |
| F | Findable | People, and computers, can find it. It has a clear name and description. | Clear folder layout and a README. |
| A | Accessible | It is clear how to get the data, and under what conditions. | README setup and access notes. |
| I | Interoperable | It uses open, standard formats that other tools can read. | CSV, not a locked format. |
| R | Reusable | Others can understand and re-use it, with a clear licence. | A README and a data dictionary. |
Here is how the two example projects score against each letter:
| Question | tidy-project/ |
messy-project/ |
|
|---|---|---|---|
| Q | Can you trust it, and do you know what was done to it? | ✔ The raw data is untouched and the code records every change | ✘ Three cleaned versions, and some values were fixed by hand |
| F | Can people find it? | ✔ Clear names and a README | ✘ data_FINAL_USE_THIS.csv |
| A | Is it clear how to get it? | ✔ The README says where everything is | ✘ “Ask Sam” |
| I | Is it in an open format? | ✔ CSV | ✘ Results in .xlsx |
| R | Can others understand and reuse it? | ✔ A data dictionary (it still needs a licence) | ✘ Columns not explained, no licence |
1. Use open file formats. Share data as CSV (comma-separated values), which is plain text that every tool can read, rather than a format that needs one program. In Excel, use File > Save As and choose CSV UTF-8. A CSV holds one sheet only, and keeps values, not formulas.
2. Describe your data. Write a data dictionary, with one row per column, as in the Documentation section, and keep it next to the data.
3. Add a licence. Without one, others don’t know whether they can reuse your work. Common choices are CC BY 4.0 for data and text, and MIT for code. The Creative Commons chooser and choosealicense.com can help. Your funder or institution may have requirements, so check first.
4. Deposit it. Put the data in a repository that gives it a permanent home and a DOI (a persistent identifier you can cite), such as Zenodo, your institution’s data repository (at Bristol this is data.bris), or one specific to your field.
Sensitive data. Some data can’t be shared openly, for example because it contains personal information. You can usually still share the metadata (the README and data dictionary) and explain how others can apply for access. Check with your research data team or ethics committee before depositing anything involving people.
For each of these three datasets, mark every letter of Q-FAIR with a ✔ or an ✘.
final_data_v7.xlsx on my laptop. Email me if you want it. I would have to remember what some of the columns mean.| Q | F | A | I | R | |
|---|---|---|---|---|---|
| A The spreadsheet | ✘ | ✘ | ✘ | ✘ | ✘ |
| B The repository CSV | ✔ | ✔ | ✔ | ✔ | ✔ |
| C The shared-drive CSV | ✔ | ✘ | partly | ✔ | ✘ |
C is documented (Q) and in an open format (I), but it is hard to find (F), you need permission to get it (A), and it has no licence (R).