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:
Is there a way to specify my working directory automatically in R.
To get the location of a script being sourced, you can use utils::getSrcDirectory
or utils::getSrcFilename
. So changing the working directory to that of the current file can be done with:
setwd(getSrcDirectory()[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.