[R] How to find the path or the current file?

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Mar 25 14:35:55 CET 2009

hacking up on gabor's solution, i've created a trivial function that
will allow you to access a file given a path relative to the path of the
file calling the function.

to be concrete, suppose you have two files -- one library and one
executable -- located in two sibling directories, and you want one of
them to access (e.g., source) the other without the need to specify the
absolute path, and irrespectively of the current working directory. 
here is a simple example.

    mkdir foo/{bin,lib} -p
    echo '
       # the library file
       foo = function() cat("foo\n")
    ' > foo/lib/lib.r

    echo '
       # the executable file
    ' > foo/bin/bin.r

now you can execute foo/bin/bin.r from whatever location, or source it
in r within whatever working directory, and still have it load

    r foo/bin/bin.r
    # foo

    (cd foo; r bin/bin.r)
    # foo

    r -e 'source("foo/bin/bin.r")'
    # foo

    (cd foo/bin; r -e 'source("bin.r")')
    # foo

so the trick for you is to source rpath, and voila.  (note, it's not
foolproof;  as duncan explained, such approach may not work in some

does this address your problem?


Gabor Grothendieck wrote:
> See:
> https://stat.ethz.ch/pipermail/r-help/2009-January/184745.html
> On Tue, Mar 24, 2009 at 7:16 AM, Marie Sivertsen <mariesivert at gmail.com> wrote:
>> Dear useRs,
>> I have a collection of source file and some of these call others.  The files
>> are distribute among a number of directories, and to know how to call some
>> other file they need to know what file is currently executed.
>> As example, I have a file 'search.R' located in directory 'bin' which needs
>> to access the file 'terms.conf' located in the directory 'conf', a sibling
>> of 'bin'.  I can have somethings like readLines('../conf/terms.conf') in
>> search.R, but this work only if search.R is executed from bin, when getwd is
>> 'bin'.  But when search.R calls from the parent as bin/search.R or any other
>> derectory then R complains that it could not find the file
>> '../conf/terms.conf'.
>> So my questions is:  how can the file search.R, when executied, discover its
>> own location and load terms.conf from <location of
>> search.R>/../conf/terms.conf?  the location of search.R can be unrelated to
>> the current directory.
>> Mvh.
>> Marie

More information about the R-help mailing list