0Pricing
R Academy · Lesson

Working Directories and File Paths

Use getwd(), setwd(), and here() for reliable cross-platform paths.

What Is the Working Directory?

The working directory is the folder R uses as a starting point when you reference files with relative paths. It is the default location R looks in (and writes to) when you do not provide a full path. Every R session has exactly one working directory at any time.

# getwd() returns the current working directory
current_dir <- getwd()
cat('Working directory:', current_dir)

# All relative file references start from this location:
# read.csv('data.csv')         <- looks in current_dir/data.csv
# source('R/helpers.R')        <- looks in current_dir/R/helpers.R

setwd() — Changing the Working Directory

setwd() changes the working directory for the current R session. It returns the previous working directory invisibly, which is useful for restoring state. Note: setwd() in scripts is discouraged in project-based workflows.

# Set a new working directory
old_dir <- setwd('/tmp')
cat('Now in:', getwd(), '\n')

# Restore original directory
setwd(old_dir)
cat('Restored to:', getwd(), '\n')

# Common anti-pattern (breaks on other machines):
# setwd('/Users/alice/Desktop/my_project')  <- hardcoded!

# Better: use RStudio Projects which set wd automatically

All lessons in this course

  1. Using source() to Load Scripts
  2. Comments, Style, and Readability
  3. Working Directories and File Paths
  4. R Projects and Workspace Management
← Back to R Academy