Set wd in RStudio

437 Views Asked by At

I am creating a series of r scripts that will be used by multiple people, meaning that the working directory of files used and stored will differ. There are two folders, one for the R code, called "rcode," and another to store the generated outputs, called "data". These two folders will always be shared in tandem. To accommodate for the changing working directory I created a "global" script that has the following lines of code and resides in the "rcode" folder:

source_path = rstudioapi::getActiveDocumentContext()$path 

setwd(dirname(source_path))

swd_data <- paste0("..\\data\\")

The first line gets the source path of the global script. The second line makes this the working directory. The third line essentially tells the script to store an output in the "data" folder, which has the same path as the "rcode" folder. So to read in a csv file within the "data" folder I write:

old_total_demand <- read.csv(paste0(swd_data, "boerne_total_demand.csv"))

When I use this script on my Windows laptop it works beautifully, but when I use it on my Mac I get the following error:

Error in file(file, "rt") : cannot open the connection

In addition: Warning message:

In file(file, "rt") :
  cannot open file '..\data\demand\boerne_total_demand.csv': No such file or directory

Would anyone have any idea why this would be? Thanks in advance for the help.

2

There are 2 best solutions below

1
AugtPelle On

I have this code from my current script at hand.

I hope you like it !


path <- dirname(getActiveDocumentContext()$path)

setwd(path)

swd_path <- paste0(path,"/data/")

if(!dir.exists(swd_path)){
  
  dir.create(swd_path)
  
}

old_total_demand <- read.csv(paste0(swd_data, "boerne_total_demand.csv"))


1
Yuka Takemon On

I'm not sure what systems your collaborators will be using, but you may run into issues due to differences between Window/Mac/Linux with regards to how paths are written. I suggest you create a R Project .Rprj using RStudio and save that in your directory that contains subdirectories for data and rcode, and share the entire project directory.

/Project_dir/MyProject.Rprj
/Project_dir/data/
/Project_dir/rcode/

Then from the R project opened through RStudio you should be able to directly refer to your data by:

data <- read.csv("data/boerne_total_demand.csv")

The working directory will always be where your .Rproj is stored, so you can avoid having to setwd as it causes lots of chaos when sharing and collaborating with others.