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

Duncan Murdoch murdoch at stats.uwo.ca
Tue Mar 24 12:45:57 CET 2009


On 24/03/2009 7:16 AM, Marie Sivertsen 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.

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




More information about the R-help mailing list