I have a script called foo.R
that includes another script other.R
, which is in the same directory:
#!/usr/bin/env Rscript
message(\
Note that the getopt package provides the get_Rscript_filename
function, which just uses the same solution presented here, but is already written for you in a standard R module, so you don't have to copy and paste the "get script path" function into every script you write.
See findSourceTraceback()
of the R.utils package, which
Finds all 'srcfile' objects generated by source() in all call frames. This makes it possible to find out which files are currently scripted by source().
The answer of rakensi from Getting path of an R script is the most correct and really brilliant IMHO. Yet, it's still a hack incorporating a dummy function. I'm quoting it here, in order to have it easier found by others.
sourceDir <- getSrcDirectory(function(dummy) {dummy})
This gives the directory of the file where the statement was placed (where the dummy function is defined). It can then be used to set the working direcory and use relative paths e.g.
setwd(sourceDir)
source("other.R")
or to create absolute paths
source(paste(sourceDir, "/other.R", sep=""))
A slimmed down variant of Supressingfire's answer:
source_local <- function(fname){
argv <- commandArgs(trailingOnly = FALSE)
base_dir <- dirname(substring(argv[grep("--file=", argv)], 8))
source(paste(base_dir, fname, sep="/"))
}
#!/usr/bin/env Rscript
print("Hello")
# sad workaround but works :(
programDir <- dirname(sys.frame(1)$ofile)
source(paste(programDir,"other.R",sep='/'))
source(paste(programDir,"other-than-other.R",sep='/'))
Steamer25's approach works, but only if there is no whitespace in the path. On macOS at least the cmdArgs[match]
returns something like /base/some~+~dir~+~with~+~whitespace/
for /base/some\ dir\ with\ whitespace/
.
I worked around this by replacing the "~+~" with a simple whitespace before returning it.
thisFile <- function() {
cmdArgs <- commandArgs(trailingOnly = FALSE)
needle <- "--file="
match <- grep(needle, cmdArgs)
if (length(match) > 0) {
# Rscript
path <- cmdArgs[match]
path <- gsub("\\~\\+\\~", " ", path)
return(normalizePath(sub(needle, "", path)))
} else {
# 'source'd via R console
return(normalizePath(sys.frames()[[1]]$ofile))
}
}
Obviously you can still extend the else block like aprstar did.