I have a script (call it Main.R) that has the following code to find itself when I run it:
frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
main.dir <- dirname(dirname(frame_files[[length(frame_files)]]))
This is used to get the directory above its own directory, main.dir, which is used to call other scripts relative to this path.
I’m interested in running this script from a command line, for example
R CMD BATCH Main.R
or
Rscript Main.R
Unfortunately, the commands above do not work when I call the script from the command line.
Is there any code I could put in Main.R or a call option to R or Rscript that I can use instead?
More specifically, the solution would need to work in Windows.
Below is a solution that will give you the correct file directory path when the script is run either with
sourceor with Rscript.The key to this is the function
normalizePath. Given a relative or abbreviated path name,normalizePathwill return a valid path or raise an error. When running the script from Rscript, if you givenormalizePaththe base filename of the current script, it’ll return the fullpath, regardless of what your current directory is. It even gets the path right when you supply a relative path to R CMD and there’s a script with the same name in the current directory!In the code above, I extract the filename from one of the strings returned by
commandArgs. If you take a look at the output ofcommandArgs, you’ll see that the filename is the 4th argument. The argument is recorded as ‘–file=yourscript.R’, so in the final line above, I split the string on ‘=’ and pull out the file name.