Skip to content

How to find the path or the current file?

7 messages · Marie Sivertsen, Duncan Murdoch, Gabor Grothendieck +1 more

#
On 24/03/2009 7:16 AM, Marie Sivertsen wrote:
In general it can't.  Since source() can work on a connection and a 
connection doesn't have to be a file, there may not be a location.

You could write your own Source function, something like this:

filenamestack <- c()

Source <- function(filename, ...) {
    # push the new filename
    filenamestack <<- c(filename, filenamestack)

    # on exit pop it off the stack
    on.exit(filenamestack <<- filenamestack[-1])

    source(filename, ...)
}

and then examine filenamestack[1] to find the name of the file currently 
being sourced.  (But Source() won't work on connections, only on filenames.)

Duncan Murdoch
#
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:
#
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
       source("http://miscell.googlecode.com/svn/rpath/rpath.r")
       source(rpath("../lib/lib.r"))
       foo()
    ' > 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
foo/lib/lib.r:

    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
circumstances.)

does this address your problem?

hilsen,
vQ
Gabor Grothendieck wrote:
#
Wacek Kusnierczyk wrote:
one thing i forgot to add:  that contrarily to what gabor warned about
his solution, you don't have to have the call to rpath at the top level,
and can embed it in nested nevironments or calls; thus, the following
executable:

    echo '
       # the executable file
       source("http://miscell.googlecode.com/svn/rpath/rpath.r")
       (function()
          (function()
             (function() {
                source(rpath("../lib/lib.r"))
                foo() })())())()
    ' > foo/bin/bin.r

will still work as below.