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

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


Below is a solution that will give you the correct file directory path when the script is run either with source or with 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 function normalizePath. Given a relative or abbreviated path name, normalizePath will return a valid path or raise an error. When running the script from Rscript, if you give normalizePath the 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 of commandArgs, 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.


On idea is to give the path as an argument to your Main.R

I Suppose You call it with RScript.

Rscript Main.R 'path' 

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

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