Is there a way to programmatically find the path of an R script inside the script itself?
I am asking this because I have several scripts that use RGtk2
and load a GUI from a .glade file.
In these scripts I am obliged to put a setwd("path/to/the/script")
instruction at the beginning, otherwise the .glade file (which is in the same directory) will not be found.
This is fine, but if I move the script in a different directory or to another computer I have to change the path. I know, it's not a big deal, but it would be nice to have something like:
setwd(getScriptPath())
So, does a similar function exist?
A path is made up of folder names. If the path is to a file, then the path will ends with a file name. The folders and files of a path are separated by a directory separator (e.g., / or \ ). Different operating systems use different directory separators. In R, the function file.
The working directory in R is the folder where you are working. Hence, it's the place (the environment) where you have to store your files of your project in order to load them or where your R objects will be saved.
Summary. getwd() is a command that is used to display the current working directory. setwd() is a command that is used to point to a specific directory list. list.files is used to get everything in the directory or folders.
This works for me:
getSrcDirectory(function(x) {x})
This defines an anonymous function (that does nothing) inside the script, and then determines the source directory of that function, which is the directory where the script is.
For RStudio only:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
This works when Running or Sourceing your file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With