Set working directory to current folder

I have been using r project file to automatically set the working directory to the current folder that contains the R script I am working on. I would like to try another approach so that my R script can run without RStudio.

Here is what I plan to do:

I add this R code to the beginning of every R script in my current folder:

setwd(here:here())

I assume this will automatically set the working directory to my current folder for every R script. Are there any problems with this workflow?

If you are inside an RStudio Project, then here::here() will find the root dir containing the .Rproj file. If thats where your scripts are located then yes, using setwd(here::here()) will set the current working directory to the root dir of the project.

actually I am thinking about using setwd(here::here()) in place of r project file.

I strongly suggest using Projects and here together.

See this and this for compelling arguments.

2 Likes