Skip to content

How to source another_file.R from within your R script

mdijkstra edited this page Sep 30, 2014 · 2 revisions

Problem description If an r_script.R is started from a location random_path, then R will use that location as work dir. This makes source(another_file.R) a hassle because the path to another_file.R is unknown. Undesirable solutions are:

  • hard code the path (e.g. /hard/coded/path/antoher_file.R). If one wants to move the scripts to another location, s/he should update the hard coded path inside the scripts as well. We argue that scripts should be location agnostic.
  • supply the scripts location as parameter when calling the script (e.g. /path/to/script/r_script.R --location /path/to/script). Doing so is a hassle and is error prone, too.

Solution Fortunately, the following code may be used to determine the location (path) of your R-script, from within the script itself. The command source(paste(path, another_file.R, sep="/")) now enables you to source the file r_script_functions.R, which is in the same directory of your script.

LocationOfThisScript = function() # Function LocationOfThisScript returns the location of this .R script (may be needed to source other files in same dir)
{
	this.file = NULL
	# This file may be 'sourced'
	for (i in -(1:sys.nframe())) {
		if (identical(sys.function(i), base::source)) this.file = (normalizePath(sys.frame(i)$ofile))
	}

	if (!is.null(this.file)) return(dirname(this.file))

	# But it may also be called from the command line
	cmd.args = commandArgs(trailingOnly = FALSE)
	cmd.args.trailing = commandArgs(trailingOnly = TRUE)
	cmd.args = cmd.args[seq.int(from=1, length.out=length(cmd.args) - length(cmd.args.trailing))]
	res = gsub("^(?:--file=(.*)|.*)$", "\\1", cmd.args)

	# If multiple --file arguments are given, R uses the last one
	res = tail(res[res != ""], 1)
	if (0 < length(res)) return(dirname(res))

	# Both are not the case. Maybe we are in an R GUI?
	return(NULL)
}
current.dir = LocationOfThisScript()
Clone this wiki locally