Chapter 4 Paths and projects

Learning goals

By the end of this chapter you should be able to:

  • Explain the difference between absolute and relative paths.
  • Use relative paths in your scripts.
  • Use an RStudio Project to keep work organised.

Prerequisites

  • You can create and save an R script in RStudio.

A tiny motivating example

If your project is organised, this will work on any computer:

read.csv("CourseData/carnivora.csv")

If your project is not organised, you end up with long absolute paths that break when shared.


4.1 File paths in plain language

A file path is the address of a file on your computer. There are two types.

4.1.1 Absolute paths (full address)

These start from the root of your computer:

  • Windows: C:/Users/YourName/Documents/Project/myData.csv
  • Mac: /Users/YourName/Documents/Project/myData.csv

Why this is a problem: Absolute paths are different on every computer, so shared code breaks.

4.2 Use an RStudio Project

What we’re about to do: Set a predictable working directory.

An RStudio Project creates a .Rproj file and sets the project folder as the working directory every time you open it.

4.2.1 How to create a project

  1. Create a folder for the course (e.g., BB852).
  2. In RStudio, go to File > New Project.
  3. Choose Existing Directory and select your folder.
  4. Click Create Project.

From now on, open the .Rproj file to work on this course. You do not need to use setwd() in your scripts.

Common mistake: Calling setwd() inside scripts. It works on your machine but fails for others.

Takeaway: RStudio Projects keep your paths stable and your work reproducible.


4.3 Suggested folder structure

Keep your project tidy:

  • CourseData/ for data files
  • scripts/ for code
  • plots/ for exported figures
  • writing/ for notes or reports

Try this: Create those folders now (if they do not already exist).


4.4 Key takeaways

  • Relative paths make your code shareable.
  • RStudio Projects fix the working directory automatically.
  • A simple folder structure saves time and confusion.

4.5 Common pitfalls recap

  • Using absolute paths in scripts.
  • Changing the working directory with setwd() and forgetting to undo it.
  • Saving data and scripts in the same messy folder.

4.6 Mini‑project

Create a new project folder with the structure above, then:

  1. Put a CSV file in CourseData/.
  2. Import it using a relative path.
  3. Write one sentence explaining why the relative path is better than the absolute one.