This post is about how to change your R working directory. You might be wondering:

Why would I want to do that?

You need this as soon as your script interacts with folders on your computer. For example for imports or exports of data or figures. So probably almost always. Let's say you have a script that creates plots and saves them in the folder "Plots", which is located in your source file directory. You have to make sure to set the working directory to your source file location. Otherwise, R will not find your folder "Plots". The same is true if you work on a script with several people: If they cloned your git repository, their paths might be different from yours even if you use relative paths. There are several ways to change the working directory to the location of your file:

Use the click interface of R Studio (I do not recommend that)

Session > Set Working Directory > To Source File Location R will print the code how to set your new working directory into the console

 setwd("~/Desktop/")

You can check your working directory with getwd()

getwd()

But this only works for jobs you're starting manually and you have to remember setting the working directory. This is error prone! Especially if you run your script on a regular basis for reports! And yes, you could copy paste your path. But what if you changed the folder structure on your computer or your poor collegue tries to run your script after cloning your repo from git? I wanted to find a way to set the working directory in an R file automatically. After reading https://stackoverflow.com/questions/13672720/r-command-for-setting-working-directory-to-source-file-location-in-rstudio and desperately trying things like

this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)`

I thought it will never work on my mac. But than I found a way:

Using the rstudioapi

Run rstudioapi::getActiveDocumentContext(). It returns a dataframe with information about your document context. Among other things, this includes the path and the name of the R file you just ran.

Document Context: 
- id:        '26462429'
- path:      '~/Desktop/MyBlog/content/post/2018-12-07-changing-working-directories.Rmd'
- contents:  <50 rows>
Document Selection:
- [33, 39] -- [33, 39]: ''
[1] "~/Desktop/MyBlog/content/post/"

Note: It is important to run rstudioapi::getActiveDocumentContext() from your R Studio editor, because you want information about your R file. If copy paste rstudioapi::getActiveDocumentContext() into the console, your context is your console and thus it will return an empty path.

Document Context: 
- id:        '#console'
- path:      ''
- contents:  <1 rows>
Document Selection:
- [1, 1] -- [1, 1]: 

You can subset the path with the $-operator. Applying regular expressions allows you to separate the path from the filename and you can set our working directory path.

# returns the path including the name of the R file you're running
completePath<- rstudioapi::getActiveDocumentContext()$path

# get the name of the R file
nameOfMyFile <- sub(".*/", "", completePath)

# exclude the R file name from the path
workingDirectoryPath <- gsub(pattern = nameOfMyFile, replacement = "", x = completePath)

setwd(workingDirectoryPath)

R Projects

Working with R Projects automatically solves your problem. Your working directory is automatically your project folder. You do not need to worry about setting working directories here.