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?
Don't ask me how it works though, because I've forgotten :/
I just worked this out myself. To ensure portability of your script always begin it with:
It works because "." translates like the Unix command $PWD. Assigning this string to a character object allows you to then insert that character object into setwd() and Presto your code will always run with its current directory as the working directory, no matter whose machine it is on or where in the file structure it is located. (Extra bonus: The wd object can be used with file.path() (ie. file.path(wd, "output_directory") to allow for the creation of a standard output directory regardless of the file path leading to your named directory. This does require you to make the new directory before referencing it this way but that, too, can be aided with the wd object.
Alternately, the following code performs the exact same thing:
or, if you don't need the file path in an object you can simply:
I tried almost everything from this question, Getting path of an R script, Get the path of current script, Find location of current .R file and R command for setting working directory to source file location in Rstudio, but at the end found myself manually browsing the CRAN table and found
scriptName
librarywhich provides
current_filename()
function, which returns proper full path of the script when sourcing in RStudio and also when invoking via R or RScript executable.The answer of rakensi from Getting path of an R script is the most correct and really brilliant IMHO. Yet, it's still a hack incorporating a dummy function. I'm quoting it here, in order to have it easier found by others.
This gives the directory of the file where the statement was placed (where the dummy function is defined). It can then be used to set the working direcory and use relative paths e.g.
or to create absolute paths
This works for me
If rather than the script,
foo.R
, knowing its path location, if you can change your code to always reference allsource
'd paths from a commonroot
then these may be a great help:Given
/app/deeply/nested/foo.R
/app/other.R
This will work
See https://krlmlr.github.io/rprojroot/ for how to define project roots.