
Image by Editor | Midjourney
Reproducible code is an integral part of modern data science. It ensures that your work is transparent, easy to share, and can be replicated by others. In R, there are several best practices you can follow to make your code more reproducible and more straightforward to collaborate on.
In this article, we’ll look at 5 best practices to help you write reproducible R code.
1. Use Project-Oriented Workflows
Organizing your work into a project structure is the first step toward reproducibility. In R, it’s recommended to use RStudio Projects. It keeps all your files in one directory. A folder structure might look like this:
my_project/ │ ├── data/ # Raw and cleaned data ├── R/ # R scripts or functions ├── output/ # Plots, tables, results ├── reports/ # R Markdown reports or presentations ├── README.md # Project overview └── .Rproj # RStudio project file
By using RStudio Projects, your project paths become relative. This makes your code portable across different machines. For example, use the here package to refer to project files like so:
library(here)
data <- read.csv(here("data", "dataset.csv"))
2. Document Your Workflow
Clear documentation is key to making your code understandable and reproducible. Use comments throughout your code to explain what each section does. When you create functions, document their purpose, inputs, and outputs. You can use the roxygen2 package to document functions directly within the code:
#' Calculate the mean of a numeric vector
#' @param x A numeric vector
#' @return Mean of the vector
mean_calc <- function(x) {
mean(x, na.rm = TRUE)
}
Also, include a README.md file in your project. This file should explain the project’s purpose, the data used, and how to run the code. It helps other users understand your work quickly and set up the environment for running the code.
3. Use Version Control
Version control is essential for keeping track of changes in your code and collaborating with others. Git is the most widely used version control system, and it integrates seamlessly with R. Use Git to commit changes regularly with clear messages about what each change does.
For example, after making a change in script.R, you can run the following commands in your terminal:
git add analysis.R # Add the file you changed git commit -m "Cleaned data and added summary stats" # Save the change with a short message
Version control also makes it easy to revert to previous versions of your code if something goes wrong. If you’re working with others, GitHub or GitLab helps you to share your code and track issues.
4. Set a Consistent Environment
Setting up a consistent environment ensures your code runs the same way on any computer. In R, you can use the renv package to manage your project’s environment. It tracks the versions of the packages you use and helps others set up the same environment.
To set up renv, run:
install.packages("renv")
renv::init() # Initialize a new environment
This will create a renv.lock file that lists the exact versions of the packages being used. Anyone else working on the project can restore the same environment by running:
renv::restore() # Restore the environment
5. Set a Seed for Randomness
When your code involves random processes, such as random sampling or model initialization, the results can change each time you run it. This makes your results hard to reproduce. To avoid this, you can set a seed for the random number generator using set.seed() in R.
For example:
set.seed(123) # Set the seed random_sample <- sample(1:100, 10) # Randomly sample 10 numbers
Conclusion
Writing reproducible code is not only a good practice, but it also ensures that your work can be easily shared, verified, and built upon. By following these five best practices—using project-oriented workflows, documenting your code, using version control, setting up a consistent environment, and setting a seed for randomness — you make your code more reliable and easier for others to replicate. These practices will help you save time, reduce errors, and ensure the integrity of your work in the long term.
