Hello, Is there a way to find where a script is located within a script? getwd() doesn't do what I want because it depends on where R was called from. I want something like source("randomFile") and within randomFile there is a function called whereAmI() which returns c:\blah\blah2\randomFile.R In perl there is a library called FindBin and $FindBin::Bin has the directory of the file that called $FindBin::Bin. [[alternative HTML version deleted]]
Not directly what you're asking for, but sourceTo() of R.utils has an argument 'chdir=FALSE' that when TRUE will change the working directory to the directory of the script being evaluated. /Henrik On Mon, Feb 22, 2010 at 9:44 PM, Rob Forler <rforler at uchicago.edu> wrote:> Hello, > > Is there a way to find where a script is located within a script? getwd() > doesn't do what I want because it depends on where R was called from. I want > something like source("randomFile") and within randomFile there is a > function called whereAmI() which returns c:\blah\blah2\randomFile.R > > In perl there is a library called FindBin and $FindBin::Bin has the > directory of the file that called $FindBin::Bin. > > ? ? ? ?[[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
There was a brief discussion about this on stackoverflow - http://stackoverflow.com/questions/1815606/rscript-determine-path-of-the-executing-script. ----- Try http://prettygraph.com Pretty Graph , the easiest way to make R-powered graphs on the web. -- View this message in context: http://n4.nabble.com/relative-file-path-tp1565112p1565166.html Sent from the R help mailing list archive at Nabble.com.
On 22/02/2010 3:44 PM, Rob Forler wrote:> Hello, > > Is there a way to find where a script is located within a script? getwd() > doesn't do what I want because it depends on where R was called from. I want > something like source("randomFile") and within randomFile there is a > function called whereAmI() which returns c:\blah\blah2\randomFile.R > > In perl there is a library called FindBin and $FindBin::Bin has the > directory of the file that called $FindBin::Bin.Some dirty code to do that would be to look back through the stack for the local variables in the source() call, and expand the filename from there. That's probably what Hadley's code was doing in the thread that Hrishi mentioned. Here's a version: whereAmI <- function() { filename <- sys.frames()[[1]]$ofile normalizePath(filename) } This works when a call to it is in a file being sourced; if there were nested source() calls, then something more elaborate like Hadley's code would be needed. And this might break tomorrow: you're not supposed to look at local variables like ofile. Duncan Murdoch