How can a script find itself in R running from the command line?

I have a script (call it Main.R ) that has the following code to find myself 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 main.dir directory, which is used to call other scripts regarding this path.

I am interested in running this script from the command line, for example

 R CMD BATCH Main.R 

or

 Rscript Main.R 

Unfortunately, the above commands do not work when I call the script from the command line.

Is there any code that I could add to Main.R or an option to call R or Rscript that I can use instead?

In particular, the solution should work on Windows.

+6
source share
2 answers

Below is a solution that will give you the correct path to the file directory when the script is launched either from source or using Rscript.

 # this is wrapped in a tryCatch. The first expression works when source executes, the # second expression works when R CMD does it. full.fpath <- tryCatch(normalizePath(parent.frame(2)$ofile), # works when using source error=function(e) # works when using R CMD normalizePath(unlist(strsplit(commandArgs()[grep('^--file=', commandArgs())], '='))[2])) dirname(full.fpath) 

The key to this is the normalizePath function. If a relative or abbreviated path name is specified, normalizePath will return a valid path or an error. When you run the script from Rscript, if you give normalizePath base file name of the current script, it will return the full path, regardless of what the current directory is. It even gets the correct path when you provide the relative path to R CMD and there is a script with the same name in the current directory!

In the above code, I am extracting the file name from one of the lines returned by commandArgs . If you look at the output of commandArgs , you will see that the file name is the 4th argument. The argument is written as "--file = yourscript.R", so in the last line above, I broke the line into "=" and pulled out the file name.

+8
source

In theory, you need to specify the path as an argument for your Main.R

Suppose you call it using RScript.

 Rscript Main.R 'path' 

in your Main.R you will add code to read the argument

 args <- commandArgs(trailingOnly = TRUE) mainpath <- as.character(args[1]) 
+1
source

All Articles