Skip to course content
Free R data course

R Foundations for Data Analysis

Unit 01.03: Relative paths are the portable ones

The single commonest reason a colleague cannot run your script is a path that only exists on your laptop.

Relative paths are the portable ones

R always has a working directory: the folder it treats as 'here'. Every path that does not start from the root of the disk is interpreted from there. data-raw/visits.csv means 'the visits file, inside data-raw, inside wherever here is'.

An absolute path names the disk instead. It embeds your username, your folder habits, and often your operating system's separators — none of which your colleague shares. It works perfectly until the moment somebody else opens the file.

The discipline is: set the working directory to the project root once, at the start, and write every path relative to it from then on.

This block writes a file, moves into the project, then moves out again.


# An absolute path is a promise only your own machine can keep.
project <- file.path(tempdir(), "paths-demo")
dir.create(file.path(project, "data-raw"), recursive = TRUE, showWarnings = FALSE)
writeLines("ward,visits\nEast,502", file.path(project, "data-raw", "visits.csv"))

old <- setwd(project)
on.exit(setwd(old))

relative <- file.path("data-raw", "visits.csv")
absolute <- file.path(getwd(), "data-raw", "visits.csv")

cat("Relative path :", relative, "\n")
cat("Reads today   :", file.exists(relative), "\n\n")
cat("Absolute path contains a username and a machine layout;\n")
cat("its length here is", nchar(absolute), "characters, and none of it\n")
cat("exists on a colleague's laptop.\n\n")

setwd(tempdir())
cat("After moving the working directory, the SAME relative path reads:",
    file.exists(relative), "\n")

Inside the project the relative path reads TRUE. The absolute path is printed with its length, and that number is a fact about this machine — a different account name gives a different number, which is the problem in miniature. Then the working directory changes and the *same* relative path reads FALSE. Nothing about the file changed; only what 'here' meant.

The mistake this prevents

The mistake is pasting an absolute path in to make an error go away. It does go away, on your machine, permanently. The failure surfaces weeks later on somebody else's, and by then the path is buried in a script nobody wants to touch.

Takeaway

Set the working directory once, then use relative paths only. If a path in your script contains your own name, it is a bug that has not been reported yet.