Skip to content
AgileLogics
5 min read

Files, Paths, and Projects

Prerequisites: Importing and exporting data

Reliable file handling is what makes an analysis easy to rerun — on your machine next month, or on a colleague's today.

Building paths

file.path("data", "raw", "sales_2025.csv")
basename("data/raw/sales_2025.csv")
tools::file_ext("sales_2025.csv")
[1] "data/raw/sales_2025.csv"
[1] "sales_2025.csv"
[1] "csv"

file.path joins parts with the right separator. Avoid absolute paths like C:/Users/ada/Desktop/data.csv in scripts — they break on every other computer.

Reading and writing text files

path <- file.path(tempdir(), "notes.txt")
writeLines(c("first line", "second line"), path)
readLines(path)
file.exists(path)
unlink(path)
file.exists(path)
[1] "first line"  "second line"
[1] TRUE
[1] FALSE

tempdir() is a safe place for temporary files; unlink() deletes files.

Listing files

dir <- file.path(tempdir(), "reports")
dir.create(dir, showWarnings = FALSE)
for (m in c("jan", "feb")) writeLines("x", file.path(dir, paste0(m, ".csv")))
writeLines("x", file.path(dir, "notes.txt"))

list.files(dir, pattern = "\\.csv$")
[1] "feb.csv" "jan.csv"

Organizing an analysis project

A consistent layout inside an RStudio Project:

sales-analysis/
├── sales-analysis.Rproj
├── data/
│   ├── raw/          # original data — never edited by hand
│   └── processed/    # cleaned data written by your scripts
├── R/                # reusable functions
├── scripts/          # 01_import.R, 02_clean.R, 03_analyse.R
├── output/           # figures and tables
└── report.qmd        # the write-up

Rules that pay off:

  • Treat raw data as read-only. All cleaning happens in code, so every step is recorded and repeatable.
  • Number your scripts in the order they run.
  • Use relative paths from the project folder. The here package (here::here("data", "raw", "sales.csv")) builds paths from the project root, wherever the code runs from.