Search code examples
rautomationworking-directory

R command for setting working directory to source file location in Rstudio


I am working out some tutorials in R. Each R code is contained in a specific folder. There are data files and other files in there. I want to open the .r file and source it such that I do not have to change the working directory in Rstudio as shown below:

enter image description here

Is there a way to specify my working directory automatically in R.


Solution

  • To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename. These require a function as an input. Create a script with the following lines, and source it to see their usage:

    print(utils::getSrcDirectory(function(){}))
    print(utils::getSrcFilename(function(){}, full.names = TRUE))
    

    Changing the working directory to that of the current file can be done with:

    setwd(getSrcDirectory(function(){})[1])
    

    This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext.

    setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
    

    This second solution requires that you are using RStudio as your IDE, of course.