Working Directories and Paths

Start clean (optional but handy)

# Clear the environment (objects in memory)
rm(list = ls())

Know where you are (working directory)

Your working directory (WD) is the folder R uses as the starting point for relative paths.

# Show current working directory
getwd()
[1] "C:/Users/ziye/Documents/GitHub/stats/general"

A relative path is specified from the working directory (e.g., data/myfile.csv).

An absolute path starts at the drive root (e.g., C:/Users/you/Documents/stats/data/myfile.csv).

Set the working directory in RStudio (every time you use a new PC)

Windows: RStudio > Tools > Global Options > General > Default working directory > Browse to your stats-main folder.

macOS: RStudio > Preferences > General(older versions: under Appearance/Pane Layout) set Default working directory to stats-main/, this is the folder with all the materials inside.

Then restart RStudio and verify:

getwd()
[1] "C:/Users/ziye/Documents/GitHub/stats/general"

Tip: In addition always save your projects inside the folder stats-main. This keeps paths stable and prevents issues.

Loading data (CSV, Excel) with relative paths

Option a) Your .qmd project is in stats-main

library(readr)
library(readxl)
df <- read_csv("data/survey.csv")
xls <- read_excel("data/survey.xlsx", sheet = 1)

Option b) Your .qmd project is in stats-main\subfolder

df <- read_csv("../data/survey.csv")
xls <- read_excel("../data/survey.xlsx", sheet = 1)

In summary:

  • read_csv(MyFile.csv) RStudio looks in the working directory for the file MyFile.csv.

  • read_csv(MyFolder/MyFile.csv) RStudio looks inside the Working Directory (WD), for the folder MyFolder, then the file MyFile.csv.

  • read_csv(data/survey.csv) RStudio looks inside the WD, looks inside data, then survey.csv.

  • read_csv(``../data/survey.csv RStudio goes up one folder from the WD, then looks for the folder dataand the file surve.csv.

You can always inspect where you are by

getwd()
[1] "C:/Users/ziye/Documents/GitHub/stats/general"
list.files()        # What’s in the working directory?
 [1] "about.qmd"           "assessment.html"     "assessment.qmd"     
 [4] "howSubmit.html"      "howSubmit.qmd"       "overview.html"      
 [7] "overview.qmd"        "reportTemplate.html" "reportTemplate.qmd" 
[10] "setup.qmd"           "wdPaths.qmd"         "wdPaths.rmarkdown"  
list.files("data")  # Do we see the data folder?
character(0)