17 Directories and Projects in R
A directory is simply a folder on your computer. R interacts with directories to read data files, write outputs, and organize a project — understanding how to check and set the working directory matters as soon as you start reading a CSV of field data or saving a plot to disk.
17.1 What Is a Working Directory?
The working directory is the default location R reads from and writes to. When you load a file such as field_yields.csv without a full path, R looks for it in the current working directory.
17.2 Checking and Setting the Working Directory
17.3 Listing Files
list.files() shows what’s available in the current directory — useful for confirming a data file actually exists before trying to read it.
17.4 Best Practices
-
Prefer RStudio Projects over
setwd()— creating an.Rprojfile (File → New Project) sets the working directory automatically to the project folder whenever it’s opened, which is more reliable than a hard-codedsetwd()call that breaks the moment the script moves to another machine or another person’s computer. -
Use relative, not absolute, paths —
"data/field_yields.csv"works on any machine;"/Users/vijay/Library/field_yields.csv"only works on one. -
Consider the
herepackage for larger projects —here::here("data", "field_yields.csv")builds a path relative to the project root regardless of which subfolder your script happens to run from, which avoids an entire category of “file not found” errors as a project grows. -
Always confirm with
getwd()before reading or saving, especially in a script you’ll hand off to someone else.
Summary
| Concept | Description |
|---|---|
| Directories and Projects in R | |
| Working Directory | The default folder R reads from and writes to. |
| Checking and Setting It | `getwd()` reports it; `setwd()` changes it. |
| Listing Files | `list.files()` shows what's in the current directory. |
| Best Practices | Prefer RStudio Projects and relative paths (or the `here` package) over hard-coded `setwd()` calls. |