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?
Amazing there is no '$0' type structure in R! You can do it with a system() call to a bash script written in R:
Then just split out the scriptpath.sh name for other.R
I couldn't get Suppressingfire's solution to work when 'source'ing from the R console.
I couldn't get hadley's solution to work when using Rscript.
Best of both worlds?
This works for me. Just greps it out of the command line arguments, strips off the unwanted text, does a dirname and finally gets the full path from that:
Steamer25's approach works, but only if there is no whitespace in the path. On macOS at least the
cmdArgs[match]
returns something like/base/some~+~dir~+~with~+~whitespace/
for/base/some\ dir\ with\ whitespace/
.I worked around this by replacing the "~+~" with a simple whitespace before returning it.
Obviously you can still extend the else block like aprstar did.
Here there is a simple solution for the problem. This command:
returns the path of the current script file. It works after the script was saved.
Note that the getopt package provides the
get_Rscript_filename
function, which just uses the same solution presented here, but is already written for you in a standard R module, so you don't have to copy and paste the "get script path" function into every script you write.