[R] Script auto-detecting its own path

Henrik Bengtsson hb at stat.berkeley.edu
Sat Oct 2 07:57:51 CEST 2010


See findSourceTraceback() of R.utils, e.g.

library("R.utils");
example(findSourceTraceback);

However, in general I would avoid using the above, because in nearly
all cases there is a better solution which does not rely on knowing
paths, e.g. setting up functions and calling those instead of using
nested source() calls.

Note also that I just fixed a minor bug, so make sure you install
R.utils v1.7.3 or newer (on CRAN).

/Henrik

On Wed, Sep 29, 2010 at 5:01 PM, Stu Field <sgf at colostate.edu> wrote:
> Hadley,
> I'm not sure this will solve the issue because if I move the script, I would still have to go into the script and edit the "/path/to/my/script.r", or do I misunderstand your workaround?
>
> I'm looking for something like:
> file.path.is.here("myscript.r")
>
> and which would return something like:
> [1] "c:/user/Desktop/"
>
> so that regardless of where the script is, as long as the accompanying scripts are in the same directory, they can be easily sourced with something like:
> dirX <- file.path.is.here("MasterScript.r")
> source(paste(dirX, "AuxillaryFile.r", sep=""))
>
> Thanks,
> Stu
>
>
>
>
> On 29 • Sep • 2010, at  15:23, Hadley Wickham wrote:
>>>
>>> Forgive me if this question has been addressed, but I was unable to find anything in the r-help list or in cyberspace. My question is this: is there a function, or set of functions, that will enable a script to detect its own path? I have tried file.path() but that was not what I was looking for. It would be nice to be able to put all the related scripts I use in the same folder with a "master" script and then source() them in that "master" script. Problem is, the "master" script must first know where it is (without me having to open it and retype the path every time I move it).
>>
>> Instead of trying to work out where your script is located, when you
>> source it in, just make sure the working directory is set correctly:
>>
>> source("/path/to/my/script.r", chdir = T)
>>
>> chdir is the very useful, but under advertised, argument to source().
>>
>> Hadley
>>
>> --
>> Assistant Professor / Dobelman Family Junior Chair
>> Department of Statistics / Rice University
>> http://had.co.nz/
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Stu Field, PhD
> Postdoctoral Fellow
> Department of Biology
> Colorado State University
> 1878 Campus Delivery
> Fort Collins, CO 80523-1878
> Office: E208 Anatomy/Zoology
> Phone: (970) 491-5744
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
>
>
>
>
>        [[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.
>
>



More information about the R-help mailing list