All in One View

Content from Introduction


Last updated on 2026-11-17 | Edit this page

Overview

Questions

  • What are R and RStudio, and how do they work together?
  • Why use R for research and data analysis?

Objectives

  • Distinguish between R and RStudio.
  • Run simple R commands and scripts.
  • Give overview of workshop contents.

R and RStudio


R is a programming language for data analysis, statistics, and visualisation. It allows you to automate analyses, create figures, and document your work so that others can reproduce your results.

RStudio is an integrated development environment (IDE) that makes working with R easier. It provides a code editor, console, file browser, and tools for viewing plots and managing projects.

Before continuing, make sure you have installed R and RStudio by following the Setup instructions.

RStudio


Throughout this workshop, we will use RStudio to write, run, and manage our R code. Although R can be used with other tools and editors, all demonstrations and exercises will use RStudio.

When you open RStudio, you will typically see:

  • Console: Run R commands interactively.
  • Source editor: Write and save reusable scripts.
  • Environment: View objects created during your session.
  • Files, Plots, and Help: Navigate files, inspect figures, and access documentation.

You can use the Console to try commands quickly, but saving your work in scripts makes it easier to reproduce and share.

Using the R Console in RStudio


Try running the following in the Console:

R

2 + 2

R can also store values in objects:

R

measurements <- c(10, 12, 15, 11, 20)
mean(measurements)

You can visualise these values:

R

plot(measurements)

This produces a scatter plot showing each measurement against its position in the vector:

Measurements of 10, 12, 15, 11, and 20 plotted against their index.

R scripts


The Console is useful for exploring data and trying out commands, but commands entered there are not automatically saved for future use.

An R script is a plain-text file, usually with the .R extension, that contains R code. Scripts allow you to organise your analysis into a sequence of steps that can be saved, rerun, and shared with others.

For example, we can combine our previous commands into a script:

R

# Create some example data
measurements <- c(10, 12, 15, 11, 20)

# Calculate the mean
print(mean(measurements))

# Visualise the measurements
plot(measurements)

In RStudio, you can create a script using File > New File > R Script and save it as analysis.R.

You can run individual lines using Ctrl+Enter (Windows/Linux) or Cmd+Enter (macOS), or run the entire script using the Source button in the script editor.

Scripts are an important step towards reproducibility: instead of manually repeating commands, you can rerun the same analysis whenever your data changes. However, a script alone does not guarantee reproducibility.

It may still depend on external files, installed packages, or settings specific to your computer.

What will you learn in this workshop?


Throughout this workshop, we will improve this project step by step:

  • Reproducibility: Understand why the analysis fails and what makes research reproducible.
  • Environments: Recreate the dependencies using renv so the code runs.
  • Code quality: Identify “code smells” and opportunities for improvement.
  • Testing: Check that changes do not break existing functionality.
  • Refactoring: Make the code easier to read and maintain.
  • Documentation: Help others understand and reuse the project.
  • Packaging: Turn the workflow into a reusable R package.

This workshop will introduce good practices to help make your R code more reproducible, maintainable, and easier to share. The principles you learn can also be applied to projects beyond R.

Code of Conduct


We aim to provide a welcoming, inclusive, and supportive learning environment for everyone. Please have a look at our Code of Conduct, which outlines expectations for respectful behaviour and how to raise concerns during the workshop.

Key Points
  • R is a programming language and RStudio is an environment for working with R.
  • Scripts make analyses easier to repeat, share, and maintain.
  • Reproducibility also depends on managing packages and computing environments.

Content from Reproducibility


Last updated on 2026-11-17 | Edit this page

Overview

Questions

  • What does it mean for a workflow to be reproducible?
  • What are the benefits of working reproducibly?
  • Does reproducibility guarantee good research?

Objectives

  • Explain what reproducibility is and how it fits alongside replicability, robustness, and generalisability.
  • Describe the advantages of making your work reproducible and who benefits from those advantages.
  • Be familiar with a set of best practices and tools (including version control, compute environment control, FAIR data, and clear documentation), that enable reproducible workflows.

A colleague’s R analysis


Before we work with real R code, let’s consider a hypothetical scenario.

Imagine a colleague has sent you their R script.

They ask you to reproduce their results while they are away.

You have the code. You know R.

It should be straightforward. Right?…

Challenge

Why is the code not running?

You try to run an R script you received from a colleague. But it fails with and error or does not run at all.

Give three possible reasons.

These are some of the most common causes:

  • Missing packages: The script may rely on packages that are not installed.
  • Incorrect file paths: The script may use file paths that only exist on your colleague’s computer.
  • Operating-system differences: An operating system, such as Windows, macOS or Linux, is the main software that manages your computer and runs programs such as R. We give an example in the How can the operating system matter? callout below.
  • Documentation missing or unclear: If the script does not explain required inputs, expected file locations, or setup steps, you may not know how to run it correctly.
  • Missing input: The script may expect other data files or inputs that were not shared with you.

If you are running the analysis on a different dataset, the script may fail because it expects specific column names, orders, or data types. This is actually a replicability issue rather than a reproducibility issue. We will cover that distinction later.

Callout

How can the operating system matter?

An operating system is the main software that manages your computer’s files, memory and hardware, and allows programs such as R to run. Windows, macOS and Linux are examples of operating systems.

The same R code can behave differently on different operating systems. So, your colleague’s script might run on their Linux computer but fail on your Windows computer because the two systems handle some tasks differently. The reverse can also happen.

For example, suppose a file in your working directory is called Small-01.csv, but your code uses a lowercase s:

R

read.csv("small-01.csv")

On your Windows computer, this code might work because filenames are usually matched regardless of capitalisation.

On your colleague’s Linux computer, it would usually fail because small-01.csv does not match Small-01.csv.

Always match the filename exactly to avoid this problem:

R

read.csv("Small-01.csv")

What is reproducibility?


A workflow is reproducible when someone else can use the same data and same analysis to obtain the same results.

But having the code doesn’t guarantee this.

You also need the right data, software versions, and instructions.

Getting the script to run is only the first hurdle.

But what if it runs and the results are different?

Challenge

Why did the results change?

Your colleague tells you which versions of packages to install and provides missing data files.

You run the script again and now it runs!

However… the results are different from your colleague’s.

Give three possible reasons for this reproducibility failure.

These are some of the most common causes:

  • Software version: R itself, or one or more packages (e.g. dplyr or ggplot2), may be a different version on your machine than on your colleague’s. Even minor version updates can change default behaviour.
  • Data: The script may rely on a specific version of a dataset, but you might be using a different copy. Files may have been edited, rows removed, variables renamed, or missing values handled differently.
  • Unclear documentation: If the workflow is poorly documented, you may unknowingly run steps differently — for example, using the wrong file, wrong parameters, or missing preprocessing steps.
  • Manual steps that are not reproducible: If your colleague performed manual data cleaning, interactive filtering, or hand-edited files, those steps may not be captured in the script. As a result, your run will not match theirs.
  • Uncontrolled randomness: Many R functions use randomness internally (e.g. sample(), bootstrapping, cross-validation). If the script does not set a random seed using set.seed(), each run can produce different results. Different machines may also use different random number generators or parallel backends, increasing variability.
  • Different computer setups: Windows, macOS and Linux can use different software to perform calculations, leading to small differences in results even with the same R code and package versions.
  • Hidden state in the workspace: If the script is run in an R session that contains objects from previous work, those objects can interfere.

What makes a workflow reproducible?


So far, we’ve encountered two problems:

  1. The script did not run.
  2. The results did not match.

What could your colleague have done differently?

Challenge

How can you increase reproducibility?

Name three tools or practices you can use to help others — and your future self — to reproduce your work.

Tools and Practices for Reproducibility

  • Version control with Git captures the exact state of your project at any point in time. This ensures the code used for an analysis workflow is preserved and recoverable, even after changes have been made later.
  • Environment management with tools like renv capture software dependencies so others can recreate your computational environment.
  • Clear documentation including READMEs, comments, and usage instructions.
  • Good data management practices like using consistent naming, metadata, and storing raw data separately from processed data.
  • Publishing code, data, and notebooks in publicly accessible repositories increases transparency and allows others to easily access your work.

What about your future self?


Imagine returning to your own analysis a year later.

The code has changed. You’ve updated your packages.

Could you still reproduce your original results?

Reproducibility isn’t just about sharing research. It’s also about being able to return to it.

Challenge

Why should research be reproducible?

Give three reasons to improve the reproducibility of the project.

Reproducibility is the essential first benchmark of trustworthy scientific research: without it, no further validation is possible.

Beyond the clear benefits for science, other reasons are:

  • Helping your future self: A reproducible workflow saves time when revisiting or updating your project later. You avoid having to reconstruct your steps from memory.
  • Collaboration: Transparent methods, shared code, use of established conventions, and clear documentation, all make it easier for others to understand, extend, and build on your work.
  • Publishability: Journals and reviewers increasingly expect accessible data and transparent methods. Easily reproducible research is more credible and more likely to be accepted.
  • Impact: Reproducible work is easier to reuse, cite, and adapt, increasing the reach and influence of your research.

Is reproducibility enough?


Back to our colleague’s analysis.

The script runs. The results match. Success!

But what if the original analysis contains a mistake?

We could reproduce that mistake too.

Reproducibility tells us whether we can obtain the same results, not whether those results are correct.

So, what else should we consider when assessing research?

Challenge

Beyond reproducibility

Reproducibility is one way to assess research, but it is not the only one.

Explore The Turing Way’s guide to reproducibility.

Find out what replicability, robustness, and generalisability mean.

Then consider:

  • How do replicability, robustness, and generalisability differ in terms of the data and analyses used?
  • What does each help us assess about the research findings?

These concepts help us assess whether research findings hold under different conditions.

Replicability

Same analysis, different data.

Do we reach similar conclusions when we repeat the analysis using a new dataset?

Replicability helps us assess whether findings depend on the original data.

Robustness

Same data, different analysis.

Do we reach similar conclusions when we analyse the same data differently?

For example, we might use different statistical methods or preprocessing choices.

Robustness helps us assess whether findings depend on a particular analytical approach.

Generalisability

Different data, different analyses, or different conditions.

Do the findings hold beyond the original study?

Generalisability considers whether conclusions apply across the populations, settings, or conditions relevant to the research question.

Diagram comparing reproducibility, replicability, robustness and generalisability by whether the data and analysis are the same or different.
The Turing Way’s illustration of reproducibility

The Turing Way Community. This illustration is created by Scriberia with The Turing Way community, used under a CC-BY 4.0 licence. DOI: 10.5281/zenodo.3332807

Good practices


Our hypothetical scenario has shown us why reproducibility matters: without it, we cannot easily check or build on research results.

But reproducibility alone is not enough. We also need code that is easy to understand, test, maintain, and reuse.

That’s where good coding practices come in.

Together, these practices help us produce more reliable, transparent, and reusable research.

What’s next?


We’ve explored these challenges through a hypothetical scenario.

Now let’s see what happens with real R code.

In the next episode, Environments, we’ll work with our colleague’s script, investigate why it fails, and learn how to manage package dependencies using renv.

Key Points
  • Reproducibility: Same data and analysis, same results.
  • Reproducible does not necessarily mean correct.
  • Replicability, robustness, and generalisability help us assess findings beyond the original analysis.
  • Good coding practices make research easier to check, maintain, and reuse.

Content from Environments


Last updated on 2026-11-17 | Edit this page

Overview

Questions

  • What is a project environment and why does it matter?
  • How can we create a project environment?

Objectives

  • Explain the purpose of an project environment.
  • Create a project environment using renv.
  • Use use renv::snapshot() to take implicit and explicit snapshots of the environment.
  • Restore an environment using a lockfile or using a DESCRIPTION file.

Running someone else’s script


A colleague emails you an R script called sleep_analysis.R and asks you to reproduce their results while they are away.

Before running anything, create an R project to organise your work.

Create an R project

Create a folder called rworkshop in your home directory to hold your workshop files. Then create an R project inside it using RStudio:

  • Go to File > New Project > New Directory > New Project
  • Name the directory sleep
  • Create it as a subdirectory of rworkshop (for example: C:/Users/username/rworkshop/)
  • Leave the other settings at their defaults, with options such as Create a git repository and Use renv with this project unticked
  • Click Create Project

To return to your work later, open sleep.Rproj in the sleep folder. Double‑clicking this file launches RStudio, sets the working directory, and restores your project as you left it.

Save the script

Download sleep_analysis.R and save it in the sleep folder. Open it in RStudio to view the code your colleague sent you:

R

library(obscurepackage)
library(ggplot2)

data <- sleep
none_transformed_data <- none_transform(data$extra)

p <- ggplot(data, aes(x = group, y = none_transformed_data)) +
  geom_boxplot() +
  labs(
    title = "Extra Sleep by Drug Group",
    x = "Drug Group",
    y = "Extra sleep (hours)"
  )

print(p)

Run the script

Run sleep_analysis.R to see what happens.

In RStudio, you can run the script using your editor’s Source button.

You will probably hit an error resulting in a message that looks like the one below.

R

Error in library(obscurepackage) : 
  there is no package called ‘obscurepackage’

The script tries to load:

R

library(obscurepackage)

On your machine, R looks for packages in its configured R libraries. You might already have ggplot2 installed, but you probably do not have obscurepackage installed, so the script fails.

Install the required packages

You may already have ggplot2 installed, but if not, you can install it with:

R

install.packages("ggplot2")

R downloads and installs ggplot2 and any required dependencies. You should see installation progress in the console, followed by the return of the > prompt. Check for errors before continuing.

The obscurepackage is not on CRAN.

First, install the remotes package, which allows you to install packages from GitHub:

R

install.packages("remotes")

R downloads and installs remotes. Wait for installation to finish and check for errors before continuing.

Then, install obscurepackage:

R

remotes::install_github("stellaprins/obscurepackage")
Challenge

Reproduce the results

Now that you have installed the required packages, are you able to reproduce the plot below?

If not, what happens, and why do you think the results differ?

Hint: visit the obscurepackage GitHub repository and explore its commit history. Have any changes been made that could explain the difference?

Boxplots of extra sleep for drug groups 1 and 2.

You will not be able to reproduce your colleague’s original plot using the latest version of obscurepackage.

Instead, you should see something like this:

Plot of extra sleep for drug groups 1 and 2, showing NA for both groups instead of boxplots.

The difference is caused by a bug introduced in a newer version of obscurepackage.

The none_transform() function was originally designed to return its input unchanged:

R

none_transform <- function(x) {
  return(x)
}

However, a bug introduced in the newer version causes the function to always return NA, regardless of its input:

R

none_transform <- function(x) {
  return(NA)
}

As a result, the analysis produces missing values instead of the expected data, preventing the original boxplot from being reproduced.

To reproduce your colleague’s results, you would need to install an earlier version of obscurepackage that does not contain the bug.

Changes to software dependencies can affect reproducibility, even when the code and data remain unchanged. This highlights the importance of recording and managing package versions.

Project environments


Different versions of an R package can behave differently.

This can be due to new features, altered defaults, or bugs, and causes the same code to produce different results.

A version mismatch happens when your script relies on a package whose behaviour has changed between releases.

A project environment helps prevent this by isolating the packages your project uses and recording their versions.

This keeps your work separate from whatever happens to be installed globally on your system and avoids conflicts between R projects that require different or incompatible dependencies.

Recording package versions in a project environment also helps you rebuild the setup, for example when someone else needs to run your analysis or you return to the project in the future.

Callout

Two different meanings of environment in R

1) project environments
These are project‑specific libraries created by the renv package. They store packages and their versions, helping you reproduce your project on other machines.

2) R environments
These store variables and track where functions were created, and control how R finds values. They enable features like lexical scoping and namespaces.

In this workshop, we are going to use an R package called renv to manage our project environment.

To install renv:

R

install.packages("renv")

R downloads and installs renv. Wait for installation to finish and check for errors before continuing.

Challenge

Find out more about renv

Open the renv help page in the R console:

R

?renv

Explore the help page and useful links.

In your own words, explain:

  • What does renv do?
  • How can renv help when handing the project over to a colleague?

renv is an R package that helps create reproducible environments.

renv gives every R project its own library of packages, separate from everything else on your computer, and records the package versions the project uses.

When you hand a project to someone else, renv can restore the package versions recorded in renv.lock.

This helps them recreate your project environment and run the analysis using the same package versions.

Differences in R versions, operating systems, or system libraries can still affect the results.

Initialise renv:

R

renv::init()

This will:

  • Set up project infrastructure inside your working directory that ensures renv will be used in future sessions
  • Discover packages used in your project and add them and their dependencies to the project library
  • Create a “lockfile” named renv.lock that records the versions of your project’s package dependencies
  • Restart R if you are using RStudio.

Install packages in the project environment

Before using renv, we installed packages using install.packages(). Packages are installed into an R library, which may be shared by several projects. When renv is active, install.packages() normally uses the project library.

This installs ggplot2 only into the project’s renv library, leaving the global library untouched:

R

renv::install("ggplot2")
Challenge

Install a GitHub package

Use the help page for renv::install to learn how to install packages inside the renv environment.

R

?renv::install
  • Use the help page to find out how to install a package from GitHub using renv::install()
  • Use what you learned to install v0.1.0 of the GitHub repository stellaprins/obscurepackage.

Hint: Explore the repository’s commit history to find the commit corresponding to v0.1.0, and check how to specify a commit hash when using renv::install().

From the help page, GitHub packages can be installed by using the username/repository string, and specific versions can be installed by supplying a commit SHA.

The commit SHA for v0.1.0 of stellaprins/obscurepackage is 9e7cfcba9bfbfd1cbea4dbc1600f8d5283c71831.

R

renv::install("stellaprins/obscurepackage@9e7cfcba9bfbfd1cbea4dbc1600f8d5283c71831")

To install a specific version of a GitHub package inside a renv project, use the username/repo@version format:

R

renv::install("stellaprins/obscurepackage@v0.1.0")

Restart your R session to make sure R uses the newly installed version of obscurepackage.

In RStudio, select Session > Restart R, or run:

R

.rs.restartR()

Note: .rs.restartR() only works in RStudio, not in a standard R terminal or other R editors.

Then run sleep_analysis.R again.

You should be able to replicate the results of your colleague!

Boxplots of extra sleep for drug groups 1 and 2, with a higher median for group 2.

Recording your environment with a lockfile


You have now reproduced your colleague’s results by installing a specific version of obscurepackage.

But how can you make sure that you, or someone else, can reproduce these results again in the future?

This is where a lockfile comes in.

When you initialise renv, it creates a file called renv.lock.

This file records information about your project’s software dependencies, including:

  • The R version used by the project
  • The packages required by the project
  • The exact versions of those packages
  • Where the packages were installed from, such as CRAN or GitHub

Now that you have installed a different version of obscurepackage, your project environment has changed.

These changes are not automatically recorded in your renv.lock file.

To check whether your project environment is consistent with your lockfile, use:

R

renv::status()

renv::status() compares three things:

  • renv project library
  • the renv.lock file
  • What your project actually uses

If these differ, renv::status() will report inconsistencies such as:

  • packages installed but not recorded
  • packages recorded but not installed
  • packages where the installed version ≠ recorded version

Once you have reviewed these differences, you can use renv::snapshot() to update the lockfile and record the current state of your project environment.

Challenge

Update your lockfile using a snapshot

Run:

R

renv::status()

Look at the output.

Now take a snapshot using renv::snapshot():

R

renv::snapshot()

Then, run renv::status() again:

R

renv::status()

Compare the renv::status outputs before and after taking a snapshot:

  • Which inconsistencies disappeared?
  • Which (if any) remain?
  • Why did snapshotting fix these issues?

After taking the snapshot, renv::status() may report:

R

No issues found -- the project is in a consistent state.

renv::snapshot() updates the lockfile to record the installed versions of your project’s dependencies and the R version.

This can resolve inconsistencies between the lockfile and the project library. However, it does not install missing packages. Some issues may still require renv::install() or renv::restore().

Use renv::snapshot() to record your project’s current package dependencies and their versions in the lockfile.

R

renv::snapshot()

Restoring an environment from a lockfile


While renv::snapshot() records your current environment, renv::restore() recreates the environment described by the lockfile.

Command Purpose
renv::status() Check whether the project environment and lockfile are consistent
renv::snapshot() Record the current environment in the lockfile
renv::restore() Recreate the environment described by the lockfile

Use renv::restore() when:

  • You open a project on a new computer
  • You clone someone else’s project from GitHub
  • You want to return to a known working state

DESCRIPTION files


You receive an email from your colleague. Apparently the earlier file (sleep_analysis.R) was the wrong one.

This time, your colleague sent you two files: sleep_analysis_final.R and DESCRIPTION.

In their message, your colleague explains that you should use the DESCRIPTION file to create the correct R environment for running the analysis.

Continue in the same sleep project. Download the DESCRIPTION file and save it in rworkshop/sleep.

Download sleep_analysis_final.R and save it in the same folder. Its contents are shown below.

R

library(dplyr)
library(ggplot2)
library(broom)

data <- sleep

# Compute group means for bar plot
summary_tbl <- data |>
  group_by(group) |>
  summarise(
    mean_extra = mean(extra),
    sd_extra   = sd(extra),
    n          = n(),
    se_extra   = sd_extra / sqrt(n)
  )

# Compute prolongation (drug - placebo) per subject
sleep1 <- data |>
  group_by(ID) |>
  summarise(
    prolongation = extra[group == 2] - extra[group == 1]
  )

# Paired t-test
tt <- t.test(sleep1$prolongation, mu = 0)
tt_tidy <- tidy(tt)

p_value <- signif(tt_tidy$p.value, 3)
t_stat  <- signif(tt_tidy$statistic, 3)

# Bar plot with t-test annotation
ggplot(summary_tbl, aes(x = factor(group), y = mean_extra)) +
  geom_col(fill = "steelblue", alpha = 0.8, width = 0.6) +
  geom_errorbar(aes(ymin = mean_extra - se_extra,
                    ymax = mean_extra + se_extra),
                width = 0.2, linewidth = 0.8) +
  labs(
    title = "Extra Sleep by Drug",
    x = "Drug",
    y = "Extra Sleep (hours)"
  ) +
  annotate(
    "text",
    x = 1.5,
    y = max(summary_tbl$mean_extra) + 1,
    label = paste0("t = ", t_stat, "\n",
                   "p = ", p_value),
    size = 5,
    hjust = 0.5
  ) +
  theme_minimal(base_size = 14)

Keep your original sleep_analysis.R file. We will compare the dependencies detected in both scripts later.

Your workshop folder should now include these files:

rworkshop/
└── sleep/
    ├── sleep.Rproj
    ├── sleep_analysis.R
    ├── sleep_analysis_final.R
    ├── DESCRIPTION
    ├── renv.lock
    ├── .Rprofile
    └── renv/
Challenge

Learn more about DESCRIPTION files

Open the DESCRIPTION file in RStudio. What information does the file contain?

The DESCRIPTION file contains information about the project, including its name, version, a short description, and the packages it depends on.

R

Package: sleepanalysis
Title: Sleep Analysis
Version: 0.1.0
Description: Dependencies for the sleep analysis.
Imports:
    dplyr (>= 1.1.0),
    tidyr (>= 1.3.0),
    ggplot2 (>= 3.4.0),
    broom (>= 0.8.0)
    

The Imports field lists the packages required by the project and their minimum versions.

The >= operator means greater than or equal to, so the specified version or any newer version can be installed.

For example, dplyr (>= 1.1.0) means that version 1.1.0 or any newer version can be used.

A DESCRIPTION file is normally used in R packages to record information such as the package name, version, authors, and dependencies.

Here, we use it to declare dependencies for our analysis project. This does not turn the project into an R package. In this case, a minimal DESCRIPTION file containing only an Imports field is sufficient to declare the project’s dependencies for use with renv.

Challenge

Why specify minimum package versions?

In DESCRIPTION files, it is common to use >= to specify the minimum required version of each package. This means that the specified version or any newer version can be installed.

Discuss the following questions: 1. What are the benefits of allowing newer package versions? 2. What potential pitfalls could this introduce?

Think back to your earlier experience with obscurepackage.

Specifying minimum versions provides flexibility, allowing projects to benefit from bug fixes, security updates, and new features without constantly updating dependency requirements.

However, newer versions can also introduce breaking changes, alter default behaviour, or contain bugs, as you saw with obscurepackage.

Therefore, specifying minimum versions alone does not guarantee reproducibility.

While DESCRIPTION defines the project’s dependency requirements, renv.lock records the exact package versions used in a particular environment.

Reset the environment

We will start with an empty package environment in the same sleep project to see which packages DESCRIPTION provides. This resets the project’s package library and lockfile, while keeping your scripts and DESCRIPTION file. Clearing objects from RStudio’s Environment pane does not reset installed packages.

Make sure the sleep project is open, then select Session > Restart R to unload packages.

Remove the packages used in the first exercise from the active library:

R

renv::remove(c("ggplot2", "obscurepackage"))

Remove the existing renv infrastructure, including the project library and lockfile:

R

renv::deactivate(clean = TRUE)

After R restarts, initialise an empty project environment:

R

renv::init(bare = TRUE)

The bare = TRUE argument skips dependency discovery and installation.

If prompted to choose how dependencies are discovered, select Use only the DESCRIPTION file (explicit mode). We will explore snapshots in more detail later in this lesson.

Try running sleep_analysis_final.R. It should fail because its required packages are not yet installed in the project library. Next, you will identify and install them.

Find dependencies in a project


Before installing anything, it is useful to check which dependencies renv detects.

renv::dependencies() scans your project files and reports every package it finds, along with where each one came from.

R

renv::dependencies()
Challenge

renv::dependencies()

Run renv::dependencies():

R

renv::dependencies()

Examine at the Package, Source, and Type columns.

  • Which packages does renv detect?
  • Which files are these packages found in?
  • Are all the detected packages listed in DESCRIPTION?

Your output may look similar to this (file paths will vary):

Finding R package dependencies ... Done!


     Type                                             Source        Package Require Version   Dev
1 Imports           C:/Users/username/rworkshop/sleep/DESCRIPTION          dplyr      >=   1.1.0 FALSE
2 Imports           C:/Users/username/rworkshop/sleep/DESCRIPTION          tidyr      >=   1.3.0 FALSE
3 Imports           C:/Users/username/rworkshop/sleep/DESCRIPTION        ggplot2      >=   3.4.0 FALSE
4 Imports           C:/Users/username/rworkshop/sleep/DESCRIPTION          broom      >=   0.8.0 FALSE
5    <NA>      C:/Users/username/rworkshop/sleep/sleep_analysis.R        ggplot2                 FALSE
6    <NA>      C:/Users/username/rworkshop/sleep/sleep_analysis.R obscurepackage                 FALSE
7    <NA> C:/Users/username/rworkshop/sleep/sleep_analysis_final.R          broom                 FALSE
8    <NA> C:/Users/username/rworkshop/sleep/sleep_analysis_final.R          dplyr                 FALSE
9    <NA> C:/Users/username/rworkshop/sleep/sleep_analysis_final.R        ggplot2                 FALSE

Which packages does renv detect?

renv detects five different packages: dplyr, tidyr, ggplot2, broom, and obscurepackage.

Some packages appear more than once because they are found in multiple files.

Which files are these packages found in?

The Source column shows where each package was found:

  • DESCRIPTION lists dplyr, tidyr, ggplot2, and broom.
  • sleep_analysis.R uses ggplot2 and obscurepackage.
  • sleep_analysis_final.R uses dplyr, ggplot2, and broom.

The Type column shows Imports for packages declared in the Imports field of DESCRIPTION. For packages detected in the R scripts, it shows <NA>.

Are all the detected packages listed in DESCRIPTION?

No. There are two differences:

  • obscurepackage is used in sleep_analysis.R but is not listed in DESCRIPTION.
  • tidyr is listed in DESCRIPTION but is not used in either R script.

This shows that the packages declared in DESCRIPTION do not always match those used in the project’s scripts.

Install dependencies from DESCRIPTION file


To install the packages listed in DESCRIPTION, we can use the remotes package.

First, install remotes if you haven’t already:

R

install.packages("remotes")

Then run:

R

remotes::install_deps()

This installs the packages listed in the DESCRIPTION file and their dependencies.

Challenge

Run both analysis scripts

Now that you have installed the dependencies from DESCRIPTION, try running both sleep_analysis.R and sleep_analysis_final.R.

Do both scripts run successfully? Why does one script fail?

sleep_analysis_final.R should run successfully.

This script uses dplyr, ggplot2, and broom, which are all listed in DESCRIPTION and have now been installed.

sleep_analysis.R should fail because it requires obscurepackage. That package is not listed in DESCRIPTION, so it was not installed. The declared dependencies support the final analysis, but not the original script.

The sleep_analysis_final.R script should now run without errors, because every required package is available inside the renv project library.

Callout

The DESCRIPTION file usually specifies minimum required versions, not exact pins.

This flexibility allows newer versions to be installed so your project can benefit from bug fixes, performance improvements, and security updates.

In contrast, the lockfile records the exact package versions used in a specific environment.

This means your colleague’s lockfile may differ from yours even if you share the same DESCRIPTION file.

Choosing which dependencies to record


Earlier, you used renv::snapshot() to record your project’s package versions in a lockfile.

But remember what you found when running renv::dependencies()? Your original sleep_analysis.R script uses obscurepackage, even though it isn’t listed in DESCRIPTION or needed for the final analysis.

When taking a snapshot, we can choose how renv identifies which packages to record.

Challenge

Snapshot types

Use the help system to find out what snapshot types are available and how they differ:

R

?renv::snapshot
  • What is the default snapshot type?
  • How do implicit and explicit snapshots differ?
  • Why is an explicit snapshot the better choice in this situation?

The default is implicit, but renv::snapshot() uses the project’s saved setting. Our project uses explicit because we selected that setting after resetting the environment.

  • An implicit snapshot records installed packages detected by renv::dependencies() in project files and their dependencies.
  • An explicit snapshot records installed packages declared in the Imports or Depends fields of DESCRIPTION and their dependencies.

Both approaches record the installed versions of the selected packages and their dependencies in the lockfile.

In our project, an implicit snapshot would identify obscurepackage because it is used in the original script.

An explicit snapshot instead uses the dependencies declared in DESCRIPTION, including tidyr, even though it is not used directly in either script.

Since our colleague has provided a DESCRIPTION file listing the packages needed for the final analysis, explicit snapshotting is the better choice here.

Check the project’s snapshot type:

R

renv::settings$snapshot.type()

The result should be "explicit". Take a snapshot using this setting:

R

renv::snapshot()

You can also specify the type for an individual snapshot:

R

renv::snapshot(type = "explicit")

Both commands use explicit mode here. Supplying type overrides the saved setting for that call only.

Check that the project is now consistent:

R

renv::status()

You should see a message indicating that there are no issues.

Your lockfile now records the dependencies for the final analysis. obscurepackage is neither installed nor recorded in the lockfile.

Challenge

Restore an environment using its lockfile

Now that you have recorded a working environment in your lockfile, let’s see how you can use it to recover a missing package.

1. Remove a package

Select Session > Restart R to unload packages, then remove broom from your project library:

R

renv::remove("broom")

2. Run your analysis

Run sleep_analysis_final.R again and examine the error message.

Why does the script no longer work?

3. Restore your environment

Think back to Restoring an environment from a lockfile, where you learned about renv::snapshot() and renv::restore().

  • Which function would you use to recover the missing package: snapshot() or restore()?
  • Try running the function you think is appropriate.
  • Run sleep_analysis_final.R again. Does it work now?
  • Why did your chosen function work (or not work)?

The script initially fails because broom has been removed from the project library, so R can no longer find the package it needs.

The correct function to use is:

R

renv::restore()

This tells renv to compare the packages installed in your project with those recorded in renv.lock. Because broom is recorded in the lockfile but is no longer installed, renv identifies the missing package and reinstalls the recorded version.

After restoring the environment, sleep_analysis_final.R should run successfully again.

Why does restore() work, but snapshot() does not?

The two functions serve different purposes:

  • renv::snapshot() records the current state of your project’s package dependencies in renv.lock.
  • renv::restore() uses the lockfile to recreate the recorded package environment.

In this exercise, the lockfile already describes a working environment. We want to recover that environment, not record its current, incomplete state.

Key Points
  • Package versions can affect results, even when code and data stay the same.
  • renv creates an isolated package library for each project.
  • DESCRIPTION declares required packages, and renv.lock records exact versions.
  • Use renv::snapshot() to record installed versions and renv::restore() to recreate the recorded package environment.

Content from Code smells


Last updated on 2026-11-17 | Edit this page

Overview

Questions

  • How can you recognise potential problems in a script before fully understanding what it does?

Objectives

  • Explain what code smells are and why identifying them is useful when exploring unfamiliar code.
  • Explain how code smells can affect readability, maintainability, correctness, and reproducibility.
  • Identify code smells in R scripts and be familiar with better approaches.

Sniffing for code smells


We have managed to get our colleague’s R workflow running and reproduce the results.

But now that we start reading the code more closely, some parts are difficult to understand.

We want to improve the code, but we don’t want to break the workflow.

Before changing anything, let’s sniff out code smells.

A code smell is a warning sign that some part of the code might be difficult to understand, maintain, or change.

Code smells are not necessarily bugs.

A script can run correctly and produce the expected results while still containing code smells.

However, smells can make it harder to:

  • Understand what the code does.
  • Find and fix mistakes.
  • Make changes without introducing new problems.
  • Reuse or maintain the analysis in the future.

We can often spot code smells without understanding the full logic of the code.

This makes looking for smells a useful first step when exploring an unfamiliar codebase.

Let’s look at some examples of common code smells.

Duplicated code


Duplicated code occurs when the same or very similar operations appear in multiple places.

This can cause different kinds of problems.

Example

Repeating a data transformation

R

sleep$extra <- sleep$extra * 2

# Later in the script
sleep$extra <- sleep$extra * 2

The first operation multiplies the values by 2.

The second operation acts on the already modified values, multiplying them by 2 again.

As a result, the original values are multiplied by 4 instead of 2.

If the second operation is accidental, the analysis will produce incorrect results, even though the code runs without errors.

WET code

Duplicated code is also associated with WET code, an informal term sometimes expanded as Write Everything Twice.

WET code repeats similar calculations or logic in different places.

For example:

R

# WET code
group1_mean <- mean(sleep$extra[sleep$group == 1])
group2_mean <- mean(sleep$extra[sleep$group == 2])

group1_sd <- sd(sleep$extra[sleep$group == 1])
group2_sd <- sd(sleep$extra[sleep$group == 2])

Here, the same calculations are written separately for each group.

Why is this a problem?

Repeated operations that modify data can accidentally apply the same transformation more than once.

Imagine we decide to handle missing values using na.rm = TRUE.

We would need to update all four calculations.

If we forget one, the groups might be analysed differently, producing inconsistent results.

As the analysis grows, maintaining repeated calculations becomes increasingly difficult.

When the same logic appears in several places, a change must be made consistently everywhere.

A better approach

An alternative is the DRY principle, which stands for Don’t Repeat Yourself.

DRY encourages us to avoid unnecessary duplication by expressing shared logic in one place.

For example, we can calculate the same statistics for both groups using dplyr:

R

# DRY code
sleep |>
  dplyr::group_by(group) |>
  dplyr::summarise(
    mean_extra = mean(extra),
    sd_extra = sd(extra),
    .groups = "drop"
  )

Here, we define each calculation once.

R then applies those calculations to each group.

If we want to change how the mean is calculated, we only need to update one line.

How do WET and DRY differ?

WET code DRY code
Repeats similar calculations Defines shared calculations once
Changes may be needed in several places Changes can often be made in one place
Greater risk of inconsistent updates Lower risk of inconsistent updates
Can become difficult to maintain as the analysis grows Often easier to maintain and extend

The goal of DRY is to avoid unnecessary duplication, not to make code shorter at the expense of readability.

What to look for

Similar blocks of code repeated with only small changes, such as different variable names or group labels.

Hardcoded paths


A hardcoded path is a file location written directly into the code.

Example

R

sleep_data <- read.csv(
  "/home/colleague/research/sleep/data/sleep.csv"
)

This code assumes that the data file is stored in a specific location on our colleague’s computer.

Why is this a problem?

The script might work perfectly for our colleague but fail when we run it on another computer.

Even if we have the same data, our files might be stored in a different directory.

This makes the workflow harder to share, reuse, and reproduce.

A better approach

Use a path relative to the project directory:

R

sleep_data <- read.csv(
  "data/sleep.csv"
)

Here, the path refers to a file inside the project’s data directory.

If we share the complete project and run the code from its root directory, the same path can work on another computer.

How do they differ?

Hardcoded absolute path Project-relative path
Refers to a specific location on a computer Refers to a location within the project
May fail on another computer More portable when the project structure is preserved

Tools such as rrtools and usethis can help create projects with a consistent structure, similar to how Cookiecutter templates are used in Python.

Following shared conventions makes it easier for collaborators to find files, understand the workflow and reproduce the analysis.

What matters most is that the structure is consistent, documented and understood by everyone working on the project.

What to look for

Absolute file paths, personal directories, or file locations that only exist on one computer.

Magic numbers


A magic number is a numerical value used in code without a clear explanation of its meaning.

Example

R

sleep$category <- ifelse(
  sleep$extra > 2.5,
  "high",
  "low"
)

Why is the threshold 2.5?

Does it come from a scientific paper, a previous analysis, or an arbitrary decision?

Why is this a problem?

Someone reading the code may not understand why the value was chosen.

If the threshold is used in several places, changing it could also lead to inconsistencies.

A better approach

Give the value a meaningful name:

R

high_response_threshold <- 2.5

sleep$category <- ifelse(
  sleep$extra > high_response_threshold,
  "high",
  "low"
)

Now the purpose of the number is easier to understand.

However, a meaningful name does not explain why the threshold was chosen. We may still need documentation or a reference to justify it.

What to look for

Unexplained numbers used in calculations, conditions, or filtering.

Commented-out code


Commented-out code is code that has been disabled by turning it into a comment.

Example

R

# sleep$category <- ifelse(sleep$extra > 1, "high", "low")
# sleep$category <- ifelse(sleep$extra > 2, "high", "low")

sleep$category <- ifelse(sleep$extra > 2.5, "high", "low")

R ignores lines beginning with #, so only the last calculation runs.

Why is this a problem?

Our colleague has left three versions of the same calculation in the script, each using a different threshold.

But which threshold is correct? Why did it change from 1 to 2, and then to 2.5?

Without an explanation, we cannot tell whether these changes were intentional or whether the older calculations are still relevant.

Commented-out code can make it difficult to identify which parts of an analysis are current and trustworthy.

A better approach

Comments are useful when they explain why something is done, rather than preserving old calculations.

For example:

R

# Classify responses using the threshold reported in
# Author et al. (2024), https://doi.org/XX.XXXX/XXXXX
high_response_threshold <- 2.5

sleep$category <- ifelse(
  sleep$extra > high_response_threshold,
  "high",
  "low"
)

This comment provides context rather than preserving an unused calculation.

Comments are not code smells themselves. The problem is leaving obsolete or unexplained code in comments.

What to look for

Disabled calculations, large blocks of commented-out code, or several alternative versions of the same analysis.

Lack of modularity


Lack of modularity occurs when different tasks are combined into one large block of code or function, rather than organised into smaller, independent parts.

Example

For example, our colleague has written a function to analyse the sleep data:

R

analyse_sleep <- function(data) {

  # Clean the data
  data <- data[!is.na(data$extra), ]
  data$group <- factor(data$group)

  # Calculate summary statistics
  summary <- aggregate(
    extra ~ group,
    data = data,
    FUN = mean
  )

  names(summary)[2] <- "mean_extra"

  # Create a plot
  plot <- ggplot2::ggplot(
    summary,
    ggplot2::aes(x = group, y = mean_extra)
  ) +
    ggplot2::geom_col() +
    ggplot2::labs(
      x = "Treatment group",
      y = "Mean change in sleep"
    )

  # Save the results
  write.csv(
    summary,
    "results/sleep_summary.csv",
    row.names = FALSE
  )

  ggplot2::ggsave(
    "results/sleep_plot.png",
    plot = plot
  )

  return(summary)
}

This function performs several different tasks:

  • Cleans and prepares the data.
  • Calculates summary statistics.
  • Creates a plot.
  • Saves the results to files.

Why is this a problem?

Imagine we only want to change the appearance of the plot.

We would still need to work inside a function that cleans the data, calculates statistics and saves files. Running the function would repeat all these steps, even though we are only interested in the plot.

Combining different tasks in one function makes it harder to understand, test and modify them independently. Changes to one part of the workflow may also affect others.

A better approach

Modular code is organised into small, self-contained parts, each with a clear purpose.

For example, we could divide our colleague’s workflow into separate functions:

R

clean_sleep_data()
summarise_sleep()
plot_sleep_results()
save_sleep_results()

Each function would be responsible for a particular task. This would make it easier to understand the workflow, test individual steps and change one part without unnecessarily affecting others.

A long function is not necessarily a problem. What matters is whether its responsibilities are clear and whether its parts are easy to understand, test and change.

What to look for

Long functions that perform several unrelated tasks.

Lack of tests


Automated tests check whether code behaves as expected. They help us catch mistakes when changing or extending an analysis.

Example

R projects using testthat commonly organise their tests as follows:

project/
├── R/
│   └── functions.R
└── tests/
    └── testthat/
        └── test-functions.R

The tests/testthat/ directory is the standard convention for R packages using testthat, although other projects may organise tests differently.

Why is this a problem?

Without tests, we have less confidence that the code works correctly or that changes will preserve its behaviour.

A better approach

Use automated tests to check expected results and identify code that has not been tested.

Test coverage measures how much of our code is executed when automated tests run.

In R, the covr package can help identify which parts of the code are covered by tests and which are not.

However, high test coverage does not guarantee correctness. Tests also need to check that the code produces the expected results.

The absence of tests does not mean the code is incorrect, but it makes changes riskier.

What to look for

Missing test files, functions without tests, assumptions about the data that are never checked, or low test coverage.

Lack of function documentation


Lack of function documentation is a code smell. A function may work correctly but still be difficult to use if its purpose, inputs and outputs are unclear.

Example

R

calculate_response <- function(data, threshold = 2.5) {
  mean(data$extra > threshold, na.rm = TRUE)
}

Why is this a problem?

What does the returned value represent? What should data contain?

A better approach

In R, functions can be documented using roxygen2, which uses comments beginning with #':

R

#' Calculate the proportion of high sleep responses
#'
#' @param data A data frame containing an `extra` column.
#' @param threshold The value above which a response is high.
#'
#' @return The proportion of non-missing observations
#'   exceeding the threshold.
calculate_response <- function(data, threshold = 2.5) {
  mean(data$extra > threshold, na.rm = TRUE)
}

The roxygen2 package can use them to generate R help files.

What to look for

Functions whose purpose, expected inputs or returned values are unclear or undocumented.

Unexplained code


Sometimes code performs an unusual operation without explaining why.

Example

R

sleep <- sleep[sleep$ID != 12, ]

Why is this a problem?

Why was participant 12 excluded? Is this intentional or a mistake?

A better approach

A useful comment can explain the decision:

R

# Exclude participant 12 because their measurements
# were affected by a known equipment failure.
sleep <- sleep[sleep$ID != 12, ]

This comment provides information that cannot be understood from the code alone.

What to look for

Unexpected exclusions, unusual calculations or important decisions without an explanation.

Overcommenting


Overcommenting occurs when comments repeat obvious operations rather than adding useful information.

Example

R

# Get the extra column
extra <- sleep$extra

# Remove missing values
extra <- extra[!is.na(extra)]

# Calculate the mean
mean_extra <- mean(extra)

# Print the result
print(mean_extra)

Why is this a problem?

These comments make the code longer without helping us understand it.

Excessive comments also require maintenance. If the code changes but the comments do not, they may become misleading.

A better approach

Rule of thumb: Code should explain what happens; comments should explain why, when the reason is not obvious.

What to look for

Unnecessary line-by-line comments, comments that simply repeat the code, or outdated explanations.

Exercises: Can you smell something?


Our colleague has shared some additional R code from different research projects.

Look at each example and identify the code smells.

You do not need to run, understand every calculation, or fix the code.

There may be more than one smell in each example.

Challenge

Exercise 1: Survey responses

R

# Read in survey results
survey <- read.csv("data/survey.csv")

# Previous approach
# get selection 
# survey$age_group <- ifelse(survey$age > 30, "older", "younger")

# get selection 
survey$age_group <- ifelse(survey$age > 35, "older", "younger")

# Calculate the mean score for female respondents
female_mean <- mean(survey$score[survey$gender == "female"])

# Calculate the mean score for male respondents
male_mean <- mean(survey$score[survey$gender == "male"])

Which code smells can you identify?

  • Magic number: The age threshold 35 is unexplained.
  • Commented-out code: An earlier age classification remains in the script.
  • Duplicated code: The mean score is calculated separately for each group.
  • Overcommenting: The comments above the mean calculations simply repeat what the code already says.
Challenge

Exercise 2: Temperature analysis

R

analyse_temperature <- function() {

  temperature <- read.csv(
    "C:/Users/researcher/Documents/weather/temperature.csv"
  )

  temperature <- na.omit(temperature)

  average <- mean(temperature$value)

  hist(temperature$value)

  write.csv(
    data.frame(average = average),
    "C:/Users/researcher/Desktop/average.csv"
  )

  return(average)
}

Which code smells can you identify?

  • Hardcoded paths: The input and output locations are specific to the researcher’s computer.
  • Lack of modularity: The function loads data, removes missing values, calculates a statistic, creates a plot and saves results.
  • Lack of function documentation: The function does not explain what temperature measurements it expects, their units or what the returned average represents.
Challenge

Exercise 3: Laboratory measurements

R

control <- measurements[measurements$treatment == "control", ]
treated <- measurements[measurements$treatment == "treated", ]

control$adjusted <- control$value * correction_factor
treated$adjusted <- treated$value * correction_factor

# Remove sample 42
treated <- treated[treated$sample_id != 42, ]

# Calculate the mean
treated_mean <- mean(treated$adjusted)

Which code smells can you identify?

  • Duplicated code: The same adjustment is performed separately for the control and treated groups.
  • Unexplained code: Sample 42 is excluded without explaining why. The comment describes the operation but not the reason.
  • Overcommenting: The comment # Calculate the mean adds no useful information.

Notice that the comment above the exclusion does not resolve the lack of explanation. A useful comment would explain why the sample was excluded.

Challenge

Exercise 4: A new colleague’s script

R

process_data <- function(data) {

  # Previous filter
  # data <- data[data$quality > minimum_quality, ]

  data <- data[data$quality >= minimum_quality, ]

  # Get the adjusted values
  data$adjusted <- data$value * adjustment_factor

  # Remove one observation
  data <- data[data$sample_id != "S018", ]

  summary <- aggregate(adjusted ~ site, data, mean)

  barplot(
    summary$adjusted,
    names.arg = summary$site
  )

  write.csv(
    summary,
    "/home/researcher/project/results/summary.csv"
  )

  return(summary)
}

Which code smells can you identify?

  • Commented-out code: An earlier filtering operation remains in the function.
  • Overcommenting: Comments such as # Get the adjusted values simply describe what the code does.
  • Unexplained code: Observation "S018" is excluded without a reason.
  • Hardcoded path: The output location is specific to the researcher’s computer.
  • Lack of modularity: The function filters and transforms data, calculates statistics, creates a plot and saves results.
  • Lack of function documentation: The function does not describe its expected input, purpose or returned result.

The variables minimum_quality and adjustment_factor are also not defined within the function. They may exist elsewhere, but this makes the function dependent on its surrounding environment.

Key Points
  • Code smells are warning signs of potential problems, even when the code runs correctly.
  • Common code smells include:
    • Duplicated code
    • Hardcoded paths
    • Magic numbers
    • Commented-out code
    • Lack of modularity
    • Missing tests
    • Poor documentation
    • Unexplained code
    • Overcommenting
  • Code smells can be identified by recognising common patterns.
  • Smells don’t always mean bugs, but they usually reduce readability and maintainability, making code harder to understand, update, and trust.
  • A smell warrants inspection as they often point to places where the code is most likely to break in the future.

Content from Documentation


Last updated on 2026-11-17 | Edit this page

Overview

Questions

  • How do different audiences influence what you document?
  • How does your intention (citation, collaboration, onboarding) shape the documentation you write?
  • What types of documentation should research software include?
  • When should you use in-code comments, and why can over-commenting be harmful?

Objectives

  • Identify and distinguish between procedural, conceptual, and reference documentation.
  • Plan documentation using the questions: Who is it for? What do they want? How else could I communicate with them?
  • Produce concise, audience-appropriate documentation.
  • Explain why it is good practice to avoid line-by-line commentary.

What is documentation?


Writing code that works is only part of making research reproducible. We also need to help others understand what our code does, how to use it and why certain decisions were made.

Documentation is information that helps people understand, use and maintain software.

It can take many forms, from a short comment explaining a decision to a website containing tutorials and reference guides.

Documentation can be divided into three broad types:

  • Procedural documentation: Explains how to do something, usually through step-by-step instructions or tutorials.
  • Conceptual documentation: Explains how and why something works, providing background information and helping users understand underlying ideas.
  • Reference documentation: Provides detailed information to look up, such as descriptions of functions, arguments and return values.

These types of documentation serve different purposes and often complement each other.

The right documentation depends on who will use the software and what they need to know.

Challenge

Exercise: Who needs what documentation?

Imagine you have expanded your colleague’s R workflow for analysing the sleep dataset into a package and now want to share it with others.

For each situation, consider:

  • Who is the documentation for?
  • What do they need to know?
  • Which type of documentation (procedural, conceptual or reference) would be most appropriate?
  1. A new colleague wants to install your R package and contribute to its development.
  2. A researcher wants to understand why you chose a particular statistical test.
  3. A researcher wants to know what a particular function in the sleep analysis does and what it returns.
  4. The head of department who made funding available for your project wants a brief update on its progress and key findings.

1. A new colleague wants to install your R package and contribute to its development.

  • Who? A colleague who is new to the project.
  • What? They need instructions for installing the package, getting started and contributing changes.
  • Type: Procedural documentation. A README and contributing guide (CONTRIBUTING.md) can provide step-by-step instructions for installation, usage and contributions.

2. A researcher wants to understand the statistical approach.

  • Who? A researcher reviewing or building on the analysis.
  • What? They need to understand why a particular statistical test was chosen and what assumptions it makes.
  • Type: Conceptual documentation. An explanation of the reasoning behind the statistical approach would help them evaluate the analysis.

3. A researcher wants to understand a function.

  • Who? Someone using or reviewing the analysis code.
  • What? They need to know what the function does, which inputs it accepts and what it returns.
  • Type: Reference documentation. A function help page would provide these details.

4. The head of department wants an update.

  • Who? Someone interested in the project’s outcomes who may not be familiar with R or the analysis code.
  • What? They need a clear summary of progress, key findings and next steps.
  • Type: Most closely related to conceptual documentation. A short, non-technical summary explaining the project’s purpose, findings and significance could be shared as a news article, blog post or project update. This is project communication rather than software documentation.

Different audiences may need different information about the same project, and not all communication needs to be technical documentation.

In this lesson, we’ll explore different ways of documenting research software, from code comments and function documentation to READMEs and documentation websites.

Writing useful code comments


Comments help explain parts of our code that might otherwise be difficult to understand. In R, ordinary comments start with #.

A useful rule of thumb is to explain why something is done, rather than simply repeating what the code does.

For example:

R

# Exclude sample 42 because its readings were affected
# by an equipment malfunction during data collection.
measurements <- measurements[measurements$sample_id != 42, ]

Compare this with a comment that simply describes the operation:

R

# Exclude sample 42
measurements <- measurements[measurements$sample_id != 42, ]

The second comment adds little because we can already see from the code that sample 42 is being excluded. What we cannot tell is why.

This is not a strict rule. Comments can also help explain what the code does when the logic is complex or not immediately obvious.

The key is to write comments that add useful information. Comments that simply repeat obvious code can make scripts harder to read and maintain, particularly if the code changes but the comments are not updated.

Documenting R functions with roxygen2


Comments can explain decisions within our code, but people using our functions also need to know what the functions do, which arguments they accept and what they return.

In R packages, we can use roxygen2 to write this documentation directly above a function. These special comments begin with #' and can be used to generate help pages.

For example:

R

#' Add two numbers
#'
#' @param x First number.
#' @param y Second number.
#' @return The sum of x and y.
#' @export
add_numbers <- function(x, y) {
  x + y
}

Here:

  • @param describes each argument.
  • @return describes what the function returns.
  • @export makes the function available to package users.

Running devtools::document() inside an R package generates help files from these comments. Users can then access the function’s documentation with ?add_numbers.

Challenge

Writing function documentation

Use roxygen2 to document the function below for people using your R package.

Include: - A short title. - @param to describe the input. - @return to describe the output. - @export to make the function available to package users.

R

double_number <- function(x) {
  x * 2
}

R

#' Double a number
#'
#' @param x A number to double.
#' @return The input multiplied by two.
#' @export
double_number <- function(x) {
  x * 2
}

@param and @return explain how to use the function; @export makes it accessible to package users.

We’ll practise generating and exploring these help pages in the Packaging episode.

Writing a useful README


Function documentation explains how to use individual functions, but someone discovering an entire project needs a broader introduction.

A README is usually a file named README.md in the project’s main directory. It provides a starting point for understanding and using the project.

At a minimum, a README should explain:

  • Purpose: What problem does the project solve, and for whom?
  • Getting started: How can someone install and use it?

For more developed packages or community projects, it should ideally also cover:

  • Features and scope: What does it do, what are its limitations and what is planned?
  • Contributing and support: How can others contribute, report issues or get help?

A README is often the first thing people see when visiting a project on GitHub, so it should help them quickly decide whether the project is relevant and how to get started.

Exploring documentation websites


For larger projects, a README and function help pages may not be enough. A documentation website can bring together tutorials, explanations, reference material, release notes and contribution guides.

The ggplot2 website is a useful example because it includes several types of documentation:

  • Get started: Introduces the package and helps beginners create their first plots.
  • Articles: Explore features and explain concepts in more detail.
  • Reference: Documents individual functions, arguments and outputs.
  • News: Records changes between package versions.
Challenge

Exploring the ggplot2 documentation

Explore the ggplot2 website.

As you browse, consider:

  • Who might use each section?
  • Can you identify procedural, conceptual and reference documentation?
  • How do tutorials and examples help users learn?
  • Why might the News section be useful for reproducibility?
  • Different audiences
    • Get started helps beginners learn the basics and create their first plots.
    • Articles help users explore particular features in more detail.
    • Reference helps users find information about specific functions and arguments.
    • News helps users understand what has changed between package versions.
  • Types of documentation
    • Procedural: Tutorials guide users through the steps needed to create plots.
    • Conceptual: Articles explain ideas and features, helping users understand how and why they work.
    • Reference: Function documentation describes what each function does, its arguments and its output.
  • Tutorials and examples
    • They demonstrate how to use the package to complete practical tasks.
    • Users can follow the examples and adapt the code for their own analyses.
  • News and reproducibility
    • The News section records changes introduced in new versions of ggplot2.
    • Checking these changes can help researchers understand differences in code behaviour or results after updating a package.

Documentation websites can also be built automatically from source files, rather than maintained as separate web pages.

For example, this workshop is written in source files and built into a website. When the source files change, the website can be rebuilt to reflect those changes.

In R, tools such as pkgdown can build documentation websites from package documentation, articles and a README. Build automation tools such as GitHub Actions can run this process when changes are pushed to a repository.

Not every project needs a full documentation website, but exploring established projects can give us ideas for documenting our own work as it grows.

Key Points
  • Research software has multiple audiences — users, developers, maintainers, and “future you” — each requiring different documentation.
  • Documentation comes in three types: procedural (step-by-step guides), conceptual (background, explanations, diagrams), and reference (APIs, parameters, system details)
  • In-code comments should be minimal and purposeful. Over-commenting distracts from the code, increases cognitive load, and often indicates unclear naming or structure.
  • Roxygen comments describe the purpose and behaviour of functions, classes, and modules. They improve readability and can be used to auto-generate reference documentation.

Content from Packaging


Last updated on 2026-11-17 | Edit this page

Overview

Questions

  • Why is it useful to organise R code into a package?
  • How do I create and develop an R package?
  • How can I check and share an R package?
  • What do package version numbers tell us?

Objectives

  • Create an R package using RStudio or usethis::create_package().
  • Organise reusable functions in the R/ directory and understand the main components of a package.
  • Declare package dependencies and test functions using devtools::load_all().
  • Document and export functions using roxygen2.
  • Install a package locally and run an analysis script that uses its functions.
  • Check a package using devtools::check() and interpret its output.
  • Describe how packages can be shared through GitHub and how version numbers communicate changes.

R packages


We’ve used several R packages throughout the previous episodes, including renv, ggplot2, dplyr, and remotes. Each of these packages provides functionality beyond what’s available in base R.

For example, to create plots using ggplot2, you can install and load the package:

R

install.packages("ggplot2")
library(ggplot2)

You now have access to functions for creating plots, such as ggplot() and geom_point().

When you install a package using install.packages(), R typically downloads it from CRAN (the Comprehensive R Archive Network), the default package repository in most R setups.

CRAN hosts thousands of packages that have been checked against a set of requirements before being made available for others to install.

When you install a package from CRAN, R will also install any required dependencies that aren’t already available on your computer.

Once a package is installed, you can load it into your current R session using library().

You only need to install a package once for a given R library, but you need to load it again in each new R session where you want to use it.

What is an R package?

An R package is a collection of code, documentation, and sometimes data, organised in a standard way that R understands. This structure makes packages easy to install, load, reuse, and share.

An excellent resource for learning about R package development is R Packages, 2nd edition, a freely available online book by Hadley Wickham and Jennifer Bryan. It covers everything from organising functions and managing dependencies to writing documentation, testing code, and preparing packages for publication.

Challenge

Why create an R package?

Visit the Introduction chapter of R Packages, 2nd edition, and read the Introduction and Philosophy sections.

As you read, consider the following questions:

  • Why might creating an R package be useful, even if you never share it with others?
  • How do the standard conventions of R packages save time and make package development easier?

Packages aren’t just for sharing code: Creating an R package allows us to bring related functions together in one place, rather than keeping them scattered across different scripts and projects. This makes our code easier to find, update, and reuse without repeatedly copying and pasting functions. Even if we never share our package with anyone else, organising our code in this way can save time and make our work easier to maintain. If we do decide to share it, others can install and use our functions just like any other R package.

Following conventions saves time and effort: R packages follow a standard structure, with R code stored in R/, tests in tests/, and data in data/. These conventions mean we don’t need to decide how to organise every new project from scratch. They also allow us to use tools designed specifically for package development. For example, usethis helps create and configure package files, while devtools provides functions for loading, testing, and checking packages. By automating these tasks, we can spend less time worrying about the details of package development and more time focusing on what our package should do.

What does an R package look like?

We’ve seen why creating an R package can be useful. But what does a package actually look like behind the scenes?

Let’s explore the structure of two packages we’ve already encountered.

Challenge

What do R packages have in common?

Explore the GitHub repositories of two packages that came up in previous episodes:

  • ggplot2: for creating plots.
  • dplyr: for manipulating data.

Take a few minutes to explore the files and folders in both repositories. You don’t need to understand the code itself; we’re interested in how the packages are organised.

  • What files and folders do both packages have in common?
  • Where are the R functions, tests, and documentation stored?
  • What differences can you spot between the two repositories?
  • Why do you think packages might need different files or folders?

Files and folders in common

Both packages share several files and folders, including R/, DESCRIPTION, NAMESPACE, man/, tests/, and README.md.

Where are the different components stored?

  • R/ contains the R functions.
  • tests/testthat/ contains automated tests.
  • man/ contains documentation for functions.
  • README.md provides an overview of the package, including what it does, how to install it, and examples of how to use it. It serves as an introduction to the package and a starting point for its documentation.

Differences between packages

Although both packages follow a common structure, they also have differences.

For example, ggplot2 includes an icons/ folder, which you won’t find in dplyr.

Packages share a standard structure, but they can also include additional files and folders depending on their purpose and development needs.

For example, ggplot2 is a data visualisation package, so its icons/ folder contains graphical assets that help illustrate its features. These are useful for ggplot2 but are not part of the standard R package structure.

Despite serving different purposes, ggplot2 and dplyr follow a recognisable structure. This is what allows R to install and load packages in a consistent way.

Creating an R package using RStudio


Now that we’ve explored how existing R packages are organised, let’s create one of our own.

Fortunately, we don’t need to create all the files and folders ourselves.

RStudio can generate the basic package structure automatically.

Creating a folder for our packages

Before creating our first package, let’s create a folder to keep our R packages together.

We’ll call this folder rpackages and use it to store the two packages we’ll create in this lesson.

  1. Open the Files pane in RStudio.
  2. Navigate to your home directory, which is your personal folder on your computer (for example, C:\Users\YourName on Windows or /home/yourname on Linux).
  3. Click New Folder.
  4. Enter rpackages as the folder name and click OK.

You should now have a folder called rpackages in your home directory.

We’ll create our first package, rstudiopackage, inside this folder using the RStudio menus.

Later, we’ll create a second package, sleep, using usethis and develop it using code from our earlier sleep analysis.

This will allow us to compare the two approaches without overwriting either package.

Creating a package using the RStudio menus

To create a package using RStudio:

  1. Go to File > New Project….
  2. Select New Directory.
  3. Select R Package.
  4. Enter rstudiopackage as the package name.
  5. Under Create project as subdirectory of, click Browse and select the rpackages folder you just created.
  6. You’ll also see some optional settings:
    • Create a git repository: Initialises a local Git repository so you can track changes to your package using version control. This doesn’t automatically create a repository on GitHub.
    • Use renv with this project: Sets up renv to manage package versions used during development, helping make your development environment reproducible. You might recognise renv from the reproducibility episode.
  7. For this exercise, leave both options unchecked.
  8. Click Create Project.

RStudio will create a directory called rstudiopackage inside rpackages and open it as a new project.

Challenge

Explore your new package

RStudio has created a new project for your package.

You might also notice that an example R script has opened automatically, containing a function called hello().

Take a few minutes to explore what RStudio has created.

  • Look at the Files pane in RStudio. What files and folders have been created?
  • Open the R/ folder and find the example hello.R script. What does the hello() function do?
  • Open the DESCRIPTION file. What information does it contain? Can you identify any placeholder values?

Package structure

Your package should contain a structure similar to this:

rpackages/
└── rstudiopackage/
    ├── .Rbuildignore
    ├── .gitignore
    ├── DESCRIPTION
    ├── NAMESPACE
    ├── R/
    │   └── hello.R
    └── rstudiopackage.Rproj

The exact files may vary depending on your RStudio version and the options you selected when creating the project.

Some hidden files, such as .gitignore, might not be visible in the Files pane.

The hello.R script

Inside R/, you’ll find an example function:

R

# Hello, world!
#
# This is an example function named 'hello' 
# which prints 'Hello, world!'.
#
# You can learn more about package authoring with RStudio at:
#
#   https://r-pkgs.org
#
# Some useful keyboard shortcuts for package authoring:
#
#   Install Package:           'Ctrl + Shift + B'
#   Check Package:             'Ctrl + Shift + E'
#   Test Package:              'Ctrl + Shift + T'

hello <- function() {
  print("Hello, world!")
}

The hello() function simply prints "Hello, world!" when called.

RStudio includes it as an example of how functions are organised inside an R package.

The DESCRIPTION file

The DESCRIPTION file contains information about your package, including its name, version, authors, description, and licence.

RStudio generates this file from a template, so some fields contain example values or placeholders.

Your file will look something like this:

Package: rstudiopackage
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Authors@R: c(
    person(
      "Jane", "Doe",
      email = "jane@example.com",
      role = c("aut", "cre")
    )
  )
Description: More about what it does (maybe more than one line).
    Continuation lines should be indented.
License: What license is it under?
Encoding: UTF-8
LazyData: true

For example, Title and Description contain instructions rather than meaningful descriptions of your package.

The author information also contains example details that need to be replaced.

These placeholders help us understand what information is expected, but we’ll need to update them as we develop the package.

Creating an R package using usethis


RStudio uses usethis behind the scenes when creating a new R package.

RStudio provides a convenient graphical interface for creating packages, but usethis can also be used directly from the R console to perform package development tasks.

Using usethis directly gives us access to a wider range of functions than those available through the RStudio interface. These functions help automate many additional package development tasks.

For example, it can:

  • Set up testing infrastructure with use_testthat(), creating the necessary files and folders and updating DESCRIPTION.
  • Add package dependencies with use_package(), updating DESCRIPTION automatically.
  • Create a README with use_readme_md(), providing a starting point for documenting the package.
  • Set up longer tutorials with use_vignette(), creating a vignette template and updating the necessary configuration.
  • Configure automated checks on GitHub with use_github_action(), creating a GitHub Actions workflow.

These tasks can be completed manually, but usethis reduces the amount of setup required and helps ensure that the necessary files and configuration are in place.

Let’s create a second package using usethis and compare it with the one we created using RStudio.

We’ll call this package sleep and save it inside the same rpackages folder. We’ll develop it using code from our earlier sleep analysis.

Creating a package with usethis::create_package()

First, install usethis if you haven’t already:

R

install.packages("usethis")

Before creating the package, we need to make sure that our working directory is set to the rpackages folder we created earlier.

You can check your current working directory using:

R

getwd()

If necessary, change your working directory using the RStudio menu:

  1. Go to Session > Set Working Directory > Choose Directory….
  2. Navigate to the rpackages folder.
  3. Click Open or Choose, depending on your operating system.

Check that your working directory is now rpackages:

R

getwd()

For example, on Windows you might see:

[1] "C:/Users/YourName/rpackages"

Your full path will differ, but it should end in rpackages.

Once you’re in the correct directory, run:

R

usethis::create_package("sleep")

This creates a new directory called sleep inside rpackages, containing the basic structure of an R package.

Depending on your RStudio settings, the new package may also open automatically as an RStudio project.

We should now have two packages stored inside rpackages:

rpackages/
├── rstudiopackage/
└── sleep/
Challenge

Compare the two packages

We now have two packages: rstudiopackage, created using RStudio, and sleep, created using usethis.

Take a few minutes to explore their files and folders.

  • What files and folders do both packages have in common?
  • Open the R/ directory in each package. Does either contain an example function?
  • Open the DESCRIPTION file in each package. What information does it contain? Can you identify any placeholder values?
  • What differences can you spot between the two packages?

Package structure

After running usethis::create_package(), your second package should contain a structure similar to this:

rpackages/
├── rstudiopackage/
│   ├── .Rbuildignore
│   ├── .gitignore
│   ├── DESCRIPTION
│   ├── NAMESPACE
│   ├── R/
│   │   └── hello.R
│   └── rstudiopackage.Rproj
└── sleep/
    ├── .Rbuildignore
    ├── .gitignore
    ├── .Rhistory
    ├── DESCRIPTION
    ├── NAMESPACE
    ├── R/
    └── sleep.Rproj

The exact files and folders may vary depending on the versions of RStudio and usethis you’re using.

Both RStudio and usethis create the basic structure of an R package, including DESCRIPTION, NAMESPACE, and R/.

One difference is that RStudio typically creates an example hello.R script inside R/, whereas usethis::create_package() does not create an example function by default.

The R/ directory in sleep will therefore initially be empty, ready for us to add our own functions.

Some files beginning with a dot (.), such as .gitignore, might not be visible in the Files pane.

The DESCRIPTION file

Both methods create a DESCRIPTION file containing information about the package, including its name, version, authors, description, and licence.

The DESCRIPTION file created by usethis, should look similar to this:

Package: sleep
Title: What the Package Does (One Line, Title Case)
Version: 0.0.0.9000
Authors@R:
    person("First", "Last", , "first.last@example.com", role = c("aut", "cre"))
Description: What the package does (one paragraph).
License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a
    license
Encoding: UTF-8
Roxygen: list(markdown = TRUE)

You may notice some differences compared with the template created using the RStudio menus.

For example, the initial version number is typically 0.0.0.9000 rather than 0.1.0.

Both templates also contain placeholder information that we’ll need to update as we develop our packages.

The structure of an R package


We’ve now created two R packages and explored their structure.

Let’s take a closer look at three core components.

Core components

Component Purpose
DESCRIPTION Contains information about the package, such as its name, version, authors, licence, and dependencies.
R/ Contains the R scripts defining the package’s functions.
NAMESPACE Contains instructions about which functions the package makes available and how it uses functions from other packages.

The DESCRIPTION file

Every R package needs a DESCRIPTION file. We’ve already seen that RStudio and usethis create it automatically with placeholder information that we can update.

The R/ directory

Every R package containing R code has an R/ directory. This directory contains the .R scripts that define the package’s functions.

We can organise related functions in one or several scripts, and filenames don’t need to match function names.

The NAMESPACE file

Each R package has its own namespace, which keeps its functions and other objects separate from those in other packages. This helps R distinguish between functions with the same name.

The NAMESPACE file contains instructions that control which functions a package makes available to users and which functions it imports from other packages.

We’ll explore this in more detail below.

More about namespaces

Two important types of namespace instructions are:

  • Exports: Functions that a package makes available to users.
  • Imports: Functions that a package brings in from other packages for use in its own code.

We can use :: to call an exported function from a specific package without first loading it with library().

For example, we used this when installing obscurepackage from GitHub:

R

remotes::install_github("stellaprins/obscurepackage")

Here, remotes is the package name, and install_github() is the function name. This works because remotes exports install_github().

When writing our own package, we can also use functions from other packages. For example, we can call dplyr::summarise() inside our functions without importing it into our namespace. Alternatively, we could import summarise() and call it without the dplyr:: prefix.

We usually don’t edit NAMESPACE manually. Instead, roxygen2 generates it from special comments in our R scripts. Later, we’ll use @export to make functions from our own package available to users.

Challenge

Why are namespaces useful?

Read Section 10.2.1, Motivation in R Packages, 2nd edition.

Using the examples in this section, explain two reasons why namespaces are useful.

Namespaces therefore help packages behave consistently, even when users define functions with the same names.

Both examples show how namespaces prevent naming conflicts. The first shows how we can use :: to choose a function, while the second shows how namespaces ensure that package functions use the correct functions internally.

1. Choosing the right function when different packages use the same name

Both here and lubridate provide a function called here(), but these functions do different things.

If we attach both packages using library(), calling here() uses the version from whichever package was attached last. This means the same function call could give different results depending on the order in which we attach the packages.

We can use :: to specify exactly which function we want:

R

here::here()
lubridate::here()

This works regardless of the order in which the packages were attached.

2. Ensuring package functions use the correct functions internally

Package functions often use other functions internally. Namespaces help them find the correct functions, even when other objects have the same names.

For example, stats::sd() uses var() to calculate standard deviations. Suppose we define our own function:

R

var <- function(x) -5

Calling var(1:5) now returns -5, but stats::sd(1:5) still works correctly. This is because sd() uses var() from the stats namespace rather than our version.

For more information, see the discussion of namespaces in R Packages, 2nd edition.

Other components

As our package develops, we may add other files and directories.

Component Purpose
man/ Help files for package functions, typically generated automatically by roxygen2.
tests/ Automated tests that check our code works as expected.
README.md An introduction to the package and how to use it.
vignettes/ Longer tutorials showing how to use the package.
data/ Datasets included with the package.

Not every package needs all these components.

However, a README.md file and automated tests are highly recommended, even for small packages, to help others understand the package and ensure it works as expected.

For more information, see the Package structure chapter of R Packages, 2nd edition.

Adding functions to our package


In our earlier sleep analysis, we used the built-in sleep dataset to calculate summary statistics for each drug group and plot the results. Let’s organise those steps into three functions in our sleep package:

  • load_sleep_data(): returns the built-in sleep dataset.
  • summarise_data(): calculates summary statistics for a chosen measurement and grouping column.
  • plot_summary(): plots group means and standard errors, with options for the bar colour and title.

Open the sleep package project in RStudio by opening sleep.Rproj inside rpackages/sleep/.

We’ll keep each function in its own script and add documentation above it using roxygen2 comments, which begin with #'. These comments describe what a function does, its inputs (@param), its output (@returns), and examples of how to use it (@examples).

load_sleep_data()

Run this command in the R console to create and open R/load_sleep_data.R:

R

usethis::use_r("load_sleep_data")

Download load_sleep_data.R and save it in the R folder.

R

#' Load the built-in sleep data
#'
#' Get the data used in our sleep analysis.
#'
#' @returns A data frame with columns extra (extra sleep in hours),
#'   group (drug group), and ID (participant).
#' @seealso [Official sleep dataset documentation](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/sleep.html)
load_sleep_data <- function() {
  datasets::sleep
}

We use datasets::sleep to refer to the built-in dataset and distinguish it from our package named sleep. This function has no inputs, so it doesn’t need an @param tag.

summarise_data()

Create and open R/summarise_data.R:

R

usethis::use_r("summarise_data")

Download summarise_data.R and save it in the R folder.

R

#' Summarise a numeric measurement by group
#'
#' Calculate the mean, standard deviation, sample size, and standard error
#' for each group.
#'
#' @param data A data frame.
#' @param value_col Name of the numeric column.
#' @param group_col Name of the grouping column.
#' @returns A data frame with group, mean, sd, n, and se.
summarise_data <- function(data, value_col = "extra", group_col = "group") {

  selected_data <- data.frame(
    group = data[[group_col]],
    value = data[[value_col]]
  )

  selected_data |>
    dplyr::summarise(
      mean = mean(value),
      sd = stats::sd(value),
      n = dplyr::n(),
      se = sd / sqrt(n),
      .by = "group"
    )
}

This function packages up the summary calculation from our earlier analysis, using the data we pass to it. The column-name arguments let us choose what to summarise and how to group it. For example, data[[value_col]] selects the column named by value_col. The defaults match the sleep dataset; .by = "group" calculates separate statistics for each group. The output always uses the same column names, so it can be passed directly to plot_summary().

plot_summary()

Create and open R/plot_summary.R:

R

usethis::use_r("plot_summary")

Download plot_summary.R and save it in the R folder.

R

#' Plot group means and standard errors
#'
#' Show means with error bars extending one standard error above and below.
#'
#' @param summary_data A data frame containing group, mean, and se.
#' @param fill Bar colour.
#' @param title Plot title.
#' @returns A ggplot object.
plot_summary <- function(summary_data, fill = "steelblue",
                         title = "Group means") {

  ggplot2::ggplot(
    summary_data,
    ggplot2::aes(x = factor(group), y = mean)
  ) +
    ggplot2::geom_col(fill = fill) +
    ggplot2::geom_errorbar(
      ggplot2::aes(ymin = mean - se, ymax = mean + se),
      width = 0.2
    ) +
    ggplot2::labs(title = title, x = "Group", y = "Mean") +
    ggplot2::theme_minimal()
}

The function expects columns named group, mean, and se, matching the output of summarise_data(). Other summary tables can also be used if they contain these columns.

Save all three scripts, then open the R/ folder in RStudio’s Files pane. You should see load_sleep_data.R, summarise_data.R, and plot_summary.R inside your package. usethis::use_r() is a convenient way to create and open them, but you can also create .R scripts manually and save them in this folder.

Testing functions using devtools


We can use devtools::load_all() to load our package functions during development without installing the package. If you haven’t already installed devtools, run install.packages("devtools") in the R console first.

First, load the package functions:

R

devtools::load_all()

Load the sleep dataset:

R

data <- load_sleep_data()

Calculate the summary statistics:

R

summary_data <- summarise_data(data)

Print the summary table:

R

print(summary_data)

You should see this table in the Console (the number of decimal places displayed may vary):

  group mean       sd  n        se
1     1 0.75 1.789010 10 0.5657345
2     2 2.33 2.002249 10 0.6331666

There is one row per drug group, with 10 observations in each group. Now plot the summaries:

R

plot_summary(summary_data)

The following plot should appear in RStudio’s Plots pane:

Bar plot of mean extra sleep for each drug group, with standard-error bars.

We can change the bar colour and title using the optional arguments:

R

plot_summary(summary_data, fill = "darkorange", title = "Extra sleep by drug")

The Plots pane should now show the same values with orange bars and the title “Extra sleep by drug”:

Orange bar plot of mean extra sleep for each drug group, with standard-error bars and the title Extra sleep by drug.

Generating help pages


Earlier, we used commands such as ?renv to access help in R. Before generating our package’s documentation, try opening the help for one of our functions:

R

?summarise_data

R cannot find a help page for this function yet. You may see a message like this:

No documentation for ‘summarise_data’ in specified packages and libraries:
you could try ‘??summarise_data’

The suggestion ??summarise_data searches help topic names, titles, and concepts across installed packages (see help.search()). It searches existing documentation, not our script comments, so it won’t find help for our function yet.

Save all three scripts, then run devtools::document() to generate these files in man/.

R

devtools::document()

The first time you generate the help files, you should see messages similar to these:

ℹ Updating sleep documentation
ℹ Loading sleep
Writing load_sleep_data.Rd
Writing plot_summary.Rd
Writing summarise_data.Rd

Each Writing message names a help file saved in your package’s man/ folder.

Reload the package so we can view the help pages during development:

R

devtools::load_all()

You should see a message confirming that the package is loading:

ℹ Loading sleep

Now open the help page for load_sleep_data():

R

?load_sleep_data

You should see this message in the Console:

ℹ Rendering development documentation for "load_sleep_data"

The documentation opens in RStudio’s Help pane, showing what the function does, what it returns, and an example of how to use it. You can open the other functions’ help pages in the same way using ?summarise_data and ?plot_summary.

When you change the documentation comments, save the script and run devtools::document() again to update the help files.

Declaring dependencies


Declare the packages used by our functions in DESCRIPTION:

R

usethis::use_package("datasets")
usethis::use_package("dplyr", min_version = "1.1.0")
usethis::use_package("ggplot2", min_version = "3.0.0")
usethis::use_package("R", type = "Depends", min_version = "4.1.0")

These commands record package dependencies in Imports and the R requirement in Depends in DESCRIPTION. The minimum versions ensure the features we use are available; >= means “this version or newer”.

Open DESCRIPTION in the Files pane. It should now include:

Depends:
    R (>= 4.1.0)
Imports:
    datasets,
    dplyr (>= 1.1.0),
    ggplot2 (>= 3.0.0)

Making our functions available


So far, we’ve used devtools::load_all() to try our functions during development. However, we also want people who install our package to be able to use them.

Earlier, we learned that a package’s NAMESPACE controls which functions are available to users. We can export our three functions by adding #' @export to their roxygen2 documentation.

For example, update R/load_sleep_data.R to include:

R

#' Load the built-in sleep data
#'
#' Get the data used in our sleep analysis.
#'
#' @returns A data frame with columns extra (extra sleep in hours),
#'   group (drug group), and ID (participant).
#' @seealso [Official sleep dataset documentation](https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/sleep.html)
#' @export
load_sleep_data <- function() {
  datasets::sleep
}

Add #' @export to the documentation for summarise_data() and plot_summary() too.

Then regenerate the documentation:

R

devtools::document()

Open the NAMESPACE file in RStudio. It should now contain:

export(load_sleep_data)
export(plot_summary)
export(summarise_data)

These instructions tell R which functions people can use after installing and loading our package. As we saw earlier, roxygen2 generates NAMESPACE automatically, so we don’t need to edit it ourselves.

Adding the analysis script


Installing our package gives others access to its functions, but doesn’t show how we used them to produce our results. For that, we also need an analysis script.

In the sleep project, create a folder called scripts/.

Download sleep_analysis.R and save it in the scripts folder.

R

# Sleep analysis
#
# Load the built-in sleep dataset, calculate and plot summary statistics
#
# Uses functions from the sleep package.

library(sleep)

data <- load_sleep_data()
summary_data <- summarise_data(data)

print(summary_data)

plot_summary(
  summary_data,
  fill = "mediumpurple",
  title = "Extra Sleep by Drug"
)

Our project now has two places for R code:

  • R/ contains reusable package functions.
  • scripts/ contains scripts that use those functions to perform an analysis.

We should commit our analysis scripts to Git alongside the package code. When we push these changes to GitHub, colleagues can access the scripts and see how our results were produced.

These scripts aren’t needed to install and use the package, so we can exclude them from the files distributed with the package:

R

usethis::use_build_ignore("scripts")

Running the analysis script

Now that we’ve exported our functions, we can install the package locally from the sleep project:

R

devtools::install()

Then run the analysis script:

R

source("scripts/sleep_analysis.R")

The script uses library(sleep) to load our installed package. It should print the summary statistics and display the plot in RStudio’s Plots pane.

Although scripts/ is excluded from the installed package, it remains in our project and can be shared through GitHub.

Checking our package


We’ve now added functions to our sleep package, generated their help pages, declared dependencies, and made the functions available to users.

We also need to check that the package follows R’s package development requirements.

We can do this using devtools::check(), which checks our package’s code, documentation, dependencies, and structure.

Run the following command in the R console:

R

devtools::check()

This runs a series of checks and reports three types of messages:

  • Errors: Problems that must be fixed.
  • Warnings: Potential problems that should be investigated.
  • Notes: Issues worth reviewing, even if the package works correctly.
Challenge

Check your package

Look at the output from devtools::check().

Your tasks:

  1. How many errors, warnings, and notes are reported?
  2. Look at the NOTES in the output. Which functions and variables are mentioned? Why might R be reporting them?

The exact results may vary depending on your package and development environment.

You might see NOTES such as:

plot_summary: no visible binding for global variable 'group'
plot_summary: no visible binding for global variable 'se'
summarise_data: no visible binding for global variable 'value'
summarise_data: no visible binding for global variable 'sd'
summarise_data: no visible binding for global variable 'n'
Undefined global functions or variables:
  group n sd se value
Consider adding
  importFrom("stats", "sd")
to your NAMESPACE file.

These NOTES refer to column names used in our summarise_data() and plot_summary() functions.

They occur because dplyr and ggplot2 recognise column names such as group, value, and se, but R’s package checker does not always recognise them.

The suggestion to import sd() relates to namespaces, which we explored earlier. However, our function already uses stats::sd() to specify which package provides the function, so we don’t need to import it separately.

These NOTES do not necessarily mean our functions are incorrect.

It’s good practice to run devtools::check() regularly as we develop our package, particularly after making changes to its functions, documentation, or dependencies.

Ideally, we should aim to resolve all errors, warnings, and notes before publishing a package, especially when submitting it to CRAN.

For more information, see:

Challenge

Resolving package check NOTES (extra)

In the previous challenge, we saw that devtools::check() reported several undefined variables in our summarise_data() and plot_summary() functions.

These NOTES occur because dplyr and ggplot2 allow us to refer directly to data-frame columns by name, but R’s package checker cannot always recognise these references.

We can resolve them using .data$column, which explicitly identifies a column in the data being processed.

Your tasks:

  1. Update summarise_data() and plot_summary() to use .data$column when referring to data-frame columns.
  2. Add rlang as a package dependency and import .data into the package namespace.
  3. Regenerate the documentation and run devtools::check() again.
  4. How many errors, warnings, and notes are now reported?

1. Update summarise_data()

Open R/summarise_data.R and replace its contents with:

R

#' Summarise a numeric measurement by group
#'
#' Calculate the mean, standard deviation, sample size, and standard error
#' for each group.
#'
#' @param data A data frame.
#' @param value_col Name of the numeric column.
#' @param group_col Name of the grouping column.
#' @returns A data frame with group, mean, sd, n, and se.
#' @importFrom rlang .data
#' @export
summarise_data <- function(data, value_col = "extra", group_col = "group") {

  selected_data <- data.frame(
    group = data[[group_col]],
    value = data[[value_col]]
  )

  selected_data |>
    dplyr::summarise(
      mean = mean(.data$value),
      sd = stats::sd(.data$value),
      n = dplyr::n(),
      se = .data$sd / sqrt(.data$n),
      .by = "group"
    )
}

Previously, we wrote mean(value). Although dplyr understands that value refers to a column, R’s package checker may treat it as an undefined variable.

Writing mean(.data$value) makes this explicit: we’re using the value column of the data being processed.

Similarly, .data$sd and .data$n refer to columns created earlier in the same summarise() call.

2. Update plot_summary()

Open R/plot_summary.R and replace its contents with:

R

#' Plot group means and standard errors
#'
#' Show means with error bars extending one standard error above and below.
#'
#' @param summary_data A data frame containing group, mean, and se.
#' @param fill Bar colour.
#' @param title Plot title.
#' @returns A ggplot object.
#' @export
plot_summary <- function(summary_data, fill = "steelblue",
                         title = "Group means") {

  ggplot2::ggplot(
    summary_data,
    ggplot2::aes(x = factor(.data$group), y = .data$mean)
  ) +
    ggplot2::geom_col(fill = fill) +
    ggplot2::geom_errorbar(
      ggplot2::aes(
        ymin = .data$mean - .data$se,
        ymax = .data$mean + .data$se
      ),
      width = 0.2
    ) +
    ggplot2::labs(title = title, x = "Group", y = "Mean") +
    ggplot2::theme_minimal()
}

Here, .data$group, .data$mean, and .data$se explicitly refer to columns in summary_data.

3. Declare the dependency

The .data pronoun is provided by the rlang package.

We’ve already added #' @importFrom rlang .data above summarise_data(). This tells roxygen2 to import .data into our package namespace.

However, as we learned earlier, importing an object from another package also requires us to declare that package as a dependency.

Run:

R

usethis::use_package("rlang", min_version = "1.0.0")

This adds rlang to the Imports field in DESCRIPTION, with a minimum required version:

rlang (>= 1.0.0)

Remember that DESCRIPTION declares which packages our package needs, while NAMESPACE specifies which objects we import from them.

4. Regenerate the documentation and check the package

Save your changes and run:

R

devtools::document()
devtools::check()

Open NAMESPACE. Alongside the existing exports, it should now contain:

importFrom(rlang,.data)

If there are no other issues, the check should report:

0 errors ✔ | 0 warnings ✔ | 0 notes ✔

Why does this work?

Using .data$column makes it explicit that we’re referring to a data-frame column rather than a separate variable.

This also connects to what we learned earlier about namespaces:

  • stats::sd() identifies the sd() function from the stats package.
  • .data$sd identifies a column called sd in the data being processed.

The original check output suggested importing sd() from stats. However, our function already uses stats::sd(), so this additional import is unnecessary. The NOTE appeared because sd was also being used as a column name.

Finally, DESCRIPTION and NAMESPACE work together: DESCRIPTION declares that our package depends on rlang, while NAMESPACE records that we import .data from it.

By making our column references explicit and declaring the dependency correctly, we resolve the NOTES without changing what our functions do.

Preparing our package for sharing


Before sharing our package, we should make sure it explains what it does, who created it, and how others can use it.

Updating DESCRIPTION

We’ve already used DESCRIPTION to declare our dependencies. Now let’s replace its placeholder information with a meaningful title, description, and author details.

For example, the main fields could look like this:

Package: sleep
Title: Summarise and Visualise Grouped Measurements
Version: 0.0.0.9000
Authors@R:
    person("First", "Last", , "first.last@example.com", role = c("aut", "cre"))
Description: Summarise numeric measurements by group using means,
    standard deviations, sample sizes, and standard errors.
    Visualise group means with standard-error bars.
    Includes a helper for loading the built-in sleep dataset.

Replace the example author details with your own. Keep the dependency and other configuration fields already present in your DESCRIPTION file.

We should also choose a licence so others know how they are allowed to use and share our code. For example, to use the MIT licence, run:

R

usethis::use_mit_license()

This creates the licence files and updates DESCRIPTION.

Adding a README

A README introduces a package and helps others get started.

Create one for our package:

R

usethis::use_readme_md()

This creates a template that we can replace with a short introduction, installation instructions, and an example.

For example:

MARKDOWN

# sleep

An R package for summarising grouped data and plotting means with standard-error bars.

## Installation

**For users:** Install the package from GitHub:

```r
install.packages("remotes")
remotes::install_github("yourusername/sleep")
```

**For developers:** Clone the repository:

```bash
git clone https://github.com/yourusername/sleep.git
```

Open `sleep.Rproj` in RStudio. Then load the package during development:

```r
install.packages("devtools")
devtools::load_all()
```

To install the package locally, use `devtools::install()`.


## License
MIT License.

Replace yourusername with your GitHub username. The installation command will work once we’ve uploaded our package to that repository.

Publishing our package


Like ggplot2 and dplyr, we can share our sleep package on GitHub. GitLab is a similar alternative for hosting and sharing code.

If you have a GitHub account, open the sleep project in RStudio and run:

R

usethis::use_git()
usethis::use_github()

The first command sets up Git to track changes, while the second helps publish our package on GitHub.

Follow the instructions in the R console to configure authentication and commit your changes.

Once published, others can install the package, just as we installed obscurepackage earlier:

R

remotes::install_github("yourusername/sleep")

Replace yourusername with your GitHub username.

They can then load the package and use our exported functions:

R

library(sleep)

data <- load_sleep_data()
summary_data <- summarise_data(data)
print(summary_data)
plot_summary(summary_data)

Alternatively, the repository can be cloned to get a local copy of the package’s source code, including its functions, documentation, and analysis scripts.

This can be done using git, by running:

BASH

git clone https://github.com/yourusername/sleep.git

This creates a folder called sleep containing the project files. They can then open sleep.Rproj in RStudio to explore the code, reproduce the analysis, or contribute to the package.

Keeping track of versions

We’ve now turned our sleep analysis into a reusable package that others can install, understand and develop further!

But what happens when we update our package? Remember how a newer version of obscurepackage changed the results in the environments episode? To keep analyses reproducible, it’s important to know which package version was used.

Our package started with:

Version: 0.0.0.9000

The .9000 indicates a development version. When we’re ready for our first release, we might change this to 0.1.0.

As we continue developing the package, we can use version numbers to communicate what has changed. A common convention is semantic versioning, which follows the format MAJOR.MINOR.PATCH:

Change Example
Bug fix (patch) 0.1.0 -> 0.1.1
New feature (minor) 1.1.0 -> 1.2.0
Breaking change (major) 1.0.0 -> 2.0.0

We can also use GitHub Releases to mark a specific version with a tag, such as v0.1.0.

Others can then install that version:

R

remotes::install_github("yourusername/sleep@v0.1.0")

Remember that changing Version in DESCRIPTION does not automatically create a GitHub tag or release.

For reproducibility, record the package version or Git commit used in an analysis, alongside the project’s renv.lock. This helps others recreate the analysis even as the package continues to evolve.

Key Points
  • R packages organise reusable code, documentation, and data in a standard structure.
  • RStudio and usethis can create package structures automatically.
  • Store functions in R/ and declare dependencies in DESCRIPTION.
  • Use devtools::load_all() to test functions during development.
  • Document and export functions using roxygen2, and generate help pages with devtools::document().
  • Use devtools::check() to identify issues before sharing a package.
  • Share packages through platforms such as GitHub and use version numbers to track changes.