tags:

views:

74

answers:

2

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?

+1  A: 

If you wrap your code in a package, you can always query parts of the package directory.
Here is an example from the RGtk2 package:

> system.file("ui", "demo.ui", package="RGtk2")
[1] "C:/opt/R/library/RGtk2/ui/demo.ui"
> 

You can do the same with a directory inst/glade/ in your sources which will become a directory glade/ in the installed package -- and system.file() will compute the path for you when installed, irrespective of the OS.

Dirk Eddelbuettel
Thanks Dirk. I really will have to start and think about putting my scripts in a package... I assume from your answer there is not a way to do it outside of a package?
nico
You can fudge something else -- set an environment variable and query that, or deparse the argument that supplied the script name to R, or ... but why not use something simple, tested, reliable and made for the purpose? ;-)
Dirk Eddelbuettel
@Dirk Eddelbuettel: Oh, of course, was just wondering if there was any other solution! Thanks!
nico
+2  A: 

Use source(..., chdir = T)

hadley
Oh, cool, didn't know about that! Thank you!
nico