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?
I liked steamer25's solution as it seems the most robust for my purposes. However, when debugging in RStudio (in windows), the path would not get set properly. The reason being that if a breakpoint is set in RStudio, sourcing the file uses an alternate "debug source" command which sets the script path a little differently. Here is the final version which I am currently using which accounts for this alternate behavior within RStudio when debugging:
My all in one!
You can wrap the r script in a bash script and retrieve the script's path as a bash variable like so:
I like this approach:
I would use a variant of @steamer25 's approach. The point is that I prefer to obtain the last sourced script even when my session was started through Rscript. The following snippet, when included on a file, will provided a variable
thisScript
containing the normalized path of the script. I confess the (ab)use of source'ing, so sometimes I invoke Rscript and the script provided in the--file
argument sources another script that sources another one... Someday I will invest in making my messy code turns into a package.I have wrapped up and extended the answers to this question into a new function
thisfile()
in rprojroot. Also works for knitting withknitr
.