The following is an incomplete list of what I think are good practices for working with R (and other programming projects).
These practices should help making your work more reproducible, intelligible to you and others, and overall easier to work with.
For more, see also the blog series what they forgot to teach you about R
Make subfolders for
This could look something like this:
-- project_directory/
| -- data/
| -- raw/
| -- processed/
| -- scripts/
| -- cleaning/
| -- analysis/
| -- writeup/
-- .gitignore
-- r_project_file.Rproj
A good readme should include
If you use RStudio, use the menu item Session > Restart R or the associated keyboard shortcut Ctrl+Shift+F10 (Windows and Linux) or Command+Shift+0 (Mac OS).
Additional keyboard shortcuts make it easy to restart development where you left off, i.e. to say “re-run all the code up to HERE”:
(We’ll get back to this when talking about working with rmarkdown / quarto)
rm(list = ls())
in your scriptsrm(list = ls())
does not remove everything in your environment (e.g. library calls, setting of working environment..)!
Caution
rm(list = ls())
does not guarantee reproducibilityTip
Use the auto-completion function in Rstudio: type ““, move the insertion point in there, and then press the tab key
Relative file paths work because they extend on your working directory. This is one reason why you should work in an R project - it sets a working directory for you, i.e. the directory where your R project is sitting in.
The here()
function retrieves your current working directory, at the time the package was loaded.
The {here} package helps especially when not working with R interactively (e.g. knitting an rmarkdown / quarto file)
[1] "/Users/au525642/Dropbox/postdoc/teaching & talks/23_PhD_R_course/course_materials"
[1] "/Users/au525642/Dropbox/postdoc/teaching & talks/23_PhD_R_course/course_materials/data/my_data_file.csv"
here()
with getwd()
[1] "/Users/au525642/Dropbox/postdoc/teaching & talks/23_PhD_R_course/course_materials"
[1] "/Users/au525642/Dropbox/postdoc/teaching & talks/23_PhD_R_course/course_materials/Day1"
The output differs because the working directory changes when the document is knitted by knitr. The here()
function still produces the expected output.
here::here()
function in an existing (or new) script