Stat-R Stat-R - 2 months ago 12
R Question

R command for setting working directory to source file location

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.

Answer

I know this question is outdated, but I was searching for a solution for that as well and Google lists this at the very top:

this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)

put that somewhere into the file (best would be the beginning, though), so that the wd is changed according to that file.

see also get filename and path of `source`d file