8.3 Making reprexes reproducible
There are three things you need to include to make your example reproducible: required packages, data, and code.
Packages should be loaded at the top of the script so it’s easy to see which ones the example needs, and check that you’re using the latest version of each package;
- you may have discovered a bug that’s been fixed since you installed or last updated the package. For packages in the tidyverse, the easiest way to check is to run
tidyverse_update()
.
- you may have discovered a bug that’s been fixed since you installed or last updated the package. For packages in the tidyverse, the easiest way to check is to run
The easiest way to include data is to use
dput()
to generate the R code needed to recreate it. For example, to recreate the mtcars dataset in R, perform the following steps:- Run dput(mtcars) in R.
- Copy the output.
- In reprex, type mtcars <-, then paste.
- Alternatively, click Addins, then Render reprex.
Spend a little bit of time ensuring that your code is easy for others to read:
Make sure you’ve used spaces and your variable names are concise yet informative.
Use comments to indicate where your problem lies.
Do your best to remove everything that is not related to the problem because the shorter your code is, the easier it is to understand and the easier it is to fix.
Try to use the smallest subset of your data that still reveals the problem, and finish by checking that you have actually made a reproducible example by starting a fresh R session and copying and pasting your script.