Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting path of an R script

Tags:

path

r

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?

like image 301
nico Avatar asked Aug 10 '10 18:08

nico


People also ask

What is a path to a file in R?

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.

What is my working directory in R?

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.

What does Getwd mean in R?

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.


2 Answers

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.

like image 91
rakensi Avatar answered Oct 05 '22 04:10

rakensi


For RStudio only:

setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) 

This works when Running or Sourceing your file.

like image 20
Richie Cotton Avatar answered Oct 05 '22 06:10

Richie Cotton