Part 37 The working directory and RStudio Projects
When you open R, it “runs” in some folder on your computer. This is the place it will look for files to import and write files as output. Think about where your class files end up when you knit them.
If you have R/RStudio closed, and you open a .R or .Rmd file, R/RStudio will start in the folder holding that file.
If you open R/RStudio from the Windows Start menu, the Mac dock, the Mac Spotlight, etc., R/Studio will start in its default location (probably your user home directory, see Tools → Global Options → General → Default working directory…).
Write all of your R scripts assuming:
You are running them by opening a fresh new R session
- Don’t use
rm(list = ls())
to clean the workspace–the workspace is already clean - You need to load required pacakges with
library()
- Don’t work on several different projects in one R session at the same time!
- Don’t use
You have all of the necessary packages installed
- Don’t include
install.packages()
calls unless they are commented out or otherwise set not to run
- Don’t include
The script will run without human input
- You need to import or load any data you are working with
- Load data and write output using R commands, not
file.choose()
,read.clipboard()
, the buttons in RStudio, etc.
All of the needed files live in your project folder
- Write relative paths, rather than absolute paths
file.path("data", "cats-data_2020-03-04.xlsx")
- Not:
/Users/brenton/Research/cats_project/data/cats-data_2020-03-04.xlsx
orC:\\Users\\brenton\\Research\\cats_project\\data\\cats-data_2020-03-04.xlsx
orfile.path("C:", "Users", "brenton", "Research", "cats_project", "data", "cats-data_2020-03-04.xlsx")
Your script might run on any system
Write the paths to files using
file.path()
orhere::here()
, rather than typing out the whole pathThis is because Windows and Mac/Linux have different syntaxes for file paths:
- Mac/Linux:
path/to/folder
- Windows:
path\\to\\folder
- Mac/Linux:
This approach has several advantages:
- Frictionless running on different computers
- Less breakage (e.g., if you move a folder around, the relative paths will still work)
- Less surprising or weird behaviors due to session crud
- Easy to tweak data/code and update results