ElvinFox
ElvinFox

Reputation: 71

How to set default working folder in Rstudio for new session?

I face the problem with changing of working directory. Here are my steps to reproduce it:

  1. Start R session (The working directory matches the one set in the settings)
  2. Change current working directory and start coding
  3. Start one more new Session (The working directory for the second session becomes the one used in the previous session but not the one set in the settings)

This is serious problem if i work with folders which contain many files as new session just fails to start

Upvotes: 0

Views: 447

Answers (1)

David
David

Reputation: 8318

You can use the following at the beginning of each script:

# set the R scripts working directory
library(rstudioapi)
current_path <- getActiveDocumentContext()$path
if (getwd() != current_path){
  setwd(dirname(current_path ))
}

This piece of code will define the working directory as the location of the script, it's really useful when working with multiple scripts that has lots of dependencies and they fail due to wrong working directory

EDIT

After understanding better the desired behaviour from the comments, you should wrap you code in a project hierarchy and set the the default working directory of the project to the desired one.

The code I added above is suitable for the case you want your scripts to run regardless of the session working directory

Upvotes: 1

Related Questions