On 12-09-21 3:27 PM, Peter Waltman wrote:> Hi -
>
> I'm curious if there is a way to get access to the location of the
calling
> script within R. I found one way of accessing it from this thread,
> https://stat.ethz.ch/pipermail/r-devel/2008-April/048914.html, which
> recommends using either:
>
> parent.frame(2)$ofile
>
> Or
>
>
> FILE <- (function() {
> attr(body(sys.function()), "srcfile")
> })()$filename
>
>
> However, those suggestions only work when you source a script from within
> the actual R shell, itself. They will both fail, though, if you try to use
> them within an executable Rscript using the shebang format (i.e.
> #!/usr/bin/Rscript or #!/usr/bin/env Rscript).
>
> Is there any way to get access to the actual file location if you are using
> an executable R script? I'm asking b/c I'd like to use an R script
that
> I've written for use w/in a workflow environment (Galaxy, to be
specific).
> Because Galaxy places the executables within a user-specified directory,
> we can't hard-code that location if we want these to be general
purpose,
> and would like access to that within the script, themselves, because in
> some cases, they need to be able to access each other.
Those both lead to R being run with the command line option --file=<your
script>. As far as I can see, R doesn't save the filename in that case,
it just opens the file and starts reading from it as though you were
entering those lines in the console, but it does save the command line,
so you can parse it yourself. For example,
-----------------------------------------
#!/usr/bin/Rscript
getFilename <- function() {
args <- commandArgs()
filearg <- grep("^--file=", args, value=TRUE)
if (length(filearg))
sub("^--file=", "", filearg)
else
invisible(NULL)
}
getFilename()
-----------------------------------------
Duncan Murdoch