Getting path of an R script

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.


Exploit the implicit "--file" argument of Rscript

When calling the script using "Rscript" (Rscript doc) the full path of the script is given as a system parameter. The following function exploits this to extract the script directory:

getScriptPath <- function(){
    cmd.args <- commandArgs()
    m <- regexpr("(?<=^--file=).+", cmd.args, perl=TRUE)
    script.dir <- dirname(regmatches(cmd.args, m))
    if(length(script.dir) == 0) stop("can't determine script dir: please call the script with Rscript")
    if(length(script.dir) > 1) stop("can't determine script dir: more than one '--file' argument detected")
    return(script.dir)
}

For RStudio only:

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

This works when Running or Sourceing your file.


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

Tags:

Path

R