What the Working Directory Is
Every R session runs "in" exactly one folder: the working directory. Whenever you use a relative path - a path that doesn't start from the root of the filesystem - R resolves it against that folder. read.csv("data.csv") doesn't mean "find data.csv somewhere on my computer"; it means "open the file called data.csv in the working directory".
This single fact explains the most common beginner error in R:
read.csv("data.csv")
# Error in file(file, "rt") : cannot open the connection
# In addition: Warning message: cannot open file 'data.csv': No such file or directory
The file exists - just not in the folder R is currently looking at. Nothing is wrong with your read.csv call; the session's working directory and the file's location disagree. The two functions below turn that from a mystery into a ten-second diagnosis.
getwd() and setwd()
getwd() (get working directory) tells you where R is looking right now:
Run that and you'll see an absolute path - the folder this session is anchored to. setwd() (set working directory) changes it:
setwd("C:/Users/rosa/projects/sales-analysis") # Windows: use / not \
setwd("/Users/rosa/projects/sales-analysis") # macOS / Linux
getwd() # confirm it took
Two mechanical notes. On Windows, write paths with / (or doubled \\) - a single \ is an escape character inside R strings, so "C:\Users" is a syntax error. And setwd() errors immediately if the folder doesn't exist, which is the friendliest failure you'll get all day: it can't leave you silently pointed at the wrong place.
The debugging routine for any "cannot open file" error is therefore: getwd() to see where R is looking, then compare it with where the file actually lives.
list.files(): See What R Sees
The third tool in the kit lists the contents of the working directory - literally the set of names a relative path can reach:
If the file you're trying to read appears in that output, read.csv("thatfile.csv") will find it. If it doesn't, no amount of retyping the read.csv line will help - the working directory is the thing to fix. list.files("data") peeks into a subfolder, and list.files(pattern = "\\.csv$") filters to CSVs only. When a filename looks right but isn't found, list.files() also exposes the classic culprits: an invisible .txt extension appended by a text editor, or Data.csv vs data.csv on a case-sensitive system.
Why Hard-Coded setwd() Breaks
Now the opinionated part. You will see scripts that open with:
setwd("C:/Users/me/Desktop/stuff/project3/final_FINAL")
That line works on exactly one machine: the author's. On your laptop, your colleague's Mac, the department server, or your own computer after a reorganize, it errors on line 1. Hard-coding an absolute path bakes one person's folder layout into code meant to outlive it.
The fix is to flip the responsibility: don't make the script find the folder - start R in the right folder, and use relative paths inside the script. Concretely:
- Use RStudio Projects. Opening a
.Rprojfile sets the working directory to the project folder automatically, on any machine. Inside the script,read.csv("data/sales.csv")then works for everyone who has the project. - Running from a terminal does the same job:
Rscript analysis.Ruses the folder you launch it from as the working directory (see running R scripts). - The here package goes one step further for those who want it -
here::here("data", "sales.csv")builds paths from the project root regardless of where the working directory has wandered - but Projects plus relative paths cover most needs without it.
setwd() itself isn't evil - it's fine interactively, when exploring. The smell is specifically an absolute, machine-specific setwd() committed at the top of a shared script.
The Workspace: ls() and rm()
Alongside "which folder am I in" sits the second piece of session state: the workspace (the global environment) - every object you've created this session. ls() lists them, rm() removes them:
The last ls() prints character(0) - an empty workspace. The incantation rm(list = ls()) reads oddly until you parse it: ls() returns the character vector of all object names, and rm(list = ...) deletes every name in that vector. It's the code equivalent of RStudio's broom icon in the Environment pane.
Know what it does not do: packages loaded with library() stay loaded, options stay set, and the working directory stays put. It clears objects, nothing else - so it is not a substitute for restarting R when you want a truly clean slate.
Clearing the Console, and the .RData Trap
Clearing the console - the scrollback of commands and output - is cosmetic and separate from clearing the workspace. In RStudio it's Ctrl+L; in code, the quirky cat("\014") sends the form-feed character, which most consoles interpret as "clear screen". Neither touches your objects.
Finally, the trap. When you quit R it offers to "save workspace image?" - writing every object to a hidden .RData file that silently reloads next time you start R in that folder. Decline, and turn it off permanently (RStudio: Tools → Global Options → uncheck "Restore .RData", set "Save workspace" to Never). A restored workspace means your session starts polluted with objects from days ago, created by code you may have since edited or deleted. Your script appears to work - because it's leaning on a stale model_v2 that nothing in the file creates anymore - right up until it runs on a clean machine and collapses.
The professional habit is the opposite: start clean, and rerun the script. If your analysis is a script that runs top to bottom in a fresh session, it's reproducible by construction; the workspace is disposable output, never precious state. Restart R often (RStudio: Session → Restart R) precisely to prove your script still stands on its own.
What You Take Away
- Relative paths resolve against the working directory;
getwd()shows it,setwd()changes it,list.files()shows what's reachable. - "Cannot open file" almost always means the working directory and the file's folder disagree - diagnose with
getwd()+list.files(). - Never commit an absolute
setwd()to a shared script - use RStudio Projects (or run the script from its folder) and relative paths. ls()lists workspace objects;rm(x)removes one;rm(list = ls())clears them all - packages and options stay.- Ctrl+L (or
cat("\014")) clears only the console text. - Don't auto-save/restore
.RData: start clean and rerun the script - that's what makes your work reproducible.
Next up: reading real data - read.csv() and friends, now that R is looking in the right folder to find them.
Frequently Asked Questions
How do I set the working directory in R?
Call setwd("path/to/folder") to change it and getwd() to see the current one. In RStudio you can also use the menu: Session → Set Working Directory. But for anything you'll rerun or share, prefer an RStudio Project (which sets the working directory automatically) over a hard-coded setwd() line - absolute paths break on every other machine.
How do I clear the environment in R?
rm(list = ls()) removes every object from the global environment: ls() lists all object names and rm() deletes them. To remove just one object, use rm(x). Note this clears objects only - loaded packages stay loaded, and the console text is untouched (that's Ctrl+L in RStudio).
Why does read.csv say 'cannot open file' when the file exists?
Because R resolves relative paths against its working directory, and yours is pointing somewhere other than the folder holding the file. Run getwd() to see where R is looking and list.files() to see what it can see there. Fix it by opening the project at the right folder (or setwd()), not by pasting an absolute path into the script.