I always encourage my students (and myself) to try to work in a reproducible manner. It is a bit slower at the start but pays dividends in the end when you have to re-do things (which happens all the time) or if you misplace some data.

To work reproducibly, when working in R / RStudio, setting the working directory is vital. It helps ensure that you know where all your source data is, and can pick up quickly where you left off.

Because I work on both Mac and PC, I tend to use Google Drive (Google Backup and Sync) to keep my files in sync at work and home.

Because Mac and PC have slightly different approaches to setting paths, I tend to include both at the start of my R scripts. I include a line of code to set the working directory for each operating system. One will fail each time, but there is no impact of this.

So here is how I do it.

setwd("~/Google Drive/Analysis")               # Tim's working directory (Mac)
setwd("C:/Users/Tim/Google Drive/Analysis")    # Tim's working directory (PC)


Slash direction on Windows

The other thing to remember is that R likes to use slashes like this / (and not these: \). This is importants as if you copy any paste the file path from Windows explorers, the slashed will be in the wrong direction.

The easiest work around I have found for this is to just set the working directory in the RStudio Interface the first time, and then copy / paste this out of the console window into your script.

Hope that is of some help!

Categories: BlogR


Adam Howes · August 2018 at 7:49 pm

Hi Tim,
Another approach you could consider, if you haven’t yet, is to use RStudio projects (https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects) alongside Git or another version control system. I’ve found it really helpful.

    Dr Timothy S Farewell · September 2018 at 7:16 am

    Thanks, Adam – yes, indeed. What you suggest is a robust approach. Thanks!

Leave a Reply