I have a script called foo.R
that includes another script other.R
, which is in the same directory:
#!/usr/bin/env Rscript
print("Hello")
source("other.R")
But I want R
to find that other.R
no matter what the current working directory.
In other words, foo.R
needs to know its own path. How can I do that?
99% of the cases you might simply use:
It will not work for crazy calls where the script is not the first argument, i.e.,
source(some args, file="myscript")
. Use @hadley's in these fancy cases.You can use the
commandArgs
function to get all the options that were passed by Rscript to the actual R interpreter and search them for--file=
. If your script was launched from the path or if it was launched with a full path, thescript.name
below will start with a'/'
. Otherwise, it must be relative to thecwd
and you can concat the two paths to get the full path.Edit: it sounds like you'd only need the
script.name
above and to strip off the final component of the path. I've removed the unneededcwd()
sample and cleaned up the main script and posted myother.R
. Just save off this script and theother.R
script into the same directory,chmod +x
them, and run the main script.main.R:
other.R:
output:
This is what I believe dehmann is looking for.
A slimmed down variant of Supressingfire's answer:
See
findSourceTraceback()
of the R.utils package, whichI had issues with the implementations above as my script is operated from a symlinked directory, or at least that's why I think the above solutions didn't work for me. Along the lines of @ennuikiller's answer, I wrapped my Rscript in bash. I set the path variable using
pwd -P
, which resolves symlinked directory structures. Then pass the path into the Rscript.Bash.sh
foo.R