# Clear the environment (objects in memory)
rm(list = ls())
Working Directories and Paths
Start clean (optional but handy)
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
).
Recommended folder layout (ENVS225)
Download the module materials, unzip them them wherever you prefer. Then un-nest the folder with the material (you will have one folder called stats-main
containing another folder inside, with the same name. Aim for:
stats-main/
├── data/
├── labs_img/
└── labs/
You can delete other sub-folders (e.g., docs) if you don’t need them. It is strongly advised to move this folder into your M: drive on university machines, so it’s accessible from every other PC on campus. Go to This PC
and access M:\(UoL userName)
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)
<- read_csv("data/survey.csv")
df <- read_excel("data/survey.xlsx", sheet = 1) xls
Option b) Your .qmd
project is in stats-main\subfolder
<- read_csv("../data/survey.csv")
df <- read_excel("../data/survey.xlsx", sheet = 1) xls
In summary:
read_csv(MyFile.csv)
RStudio looks in the working directory for the fileMyFile.csv
.read_csv(MyFolder/MyFile.csv)
RStudio looks inside the Working Directory (WD), for the folderMyFolder
, then the fileMyFile.csv
.read_csv(data/survey.csv)
RStudio looks inside the WD, looks insidedata
, thensurvey.csv
.read_csv(``../data/survey.csv
RStudio goes up one folder from the WD, then looks for the folderdata
and the filesurve.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)