Getting path of an R script

Solution 1:

This works for me:

getSrcDirectory(function(x) {x})

This defines an anonymous function (that does nothing) inside the script, and then determines the source directory of that function, which is the directory where the script is.

Solution 2:

For RStudio only:

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

This works when Running or Sourceing your file.

Solution 3:

Use source("yourfile.R", chdir = T)