[R] filename of source file

Thomas Lumley tlumley at u.washington.edu
Mon Aug 5 18:16:33 CEST 2002

On Mon, 5 Aug 2002, Jim Lemon wrote:

> David Richmond wrote:
> > Yes, source refers to the use of the source() function. Suppose I invoke
> > a file like so:
> >
> > source("/path/name/filename.r")
> >
> > I want to insert a command in filename.r like so:
> >
> > fullpath <- magic_command()
> >
> > such that fullpath is now "/path/name/filename.r"
> >
> How about
> source(fullpath<-"/path/name/filename.r") ?

That will work only when run at the top level.

If it isn't sufficient to know the directory


in which case magic.command() is getwd(), there isn't a nice way to do it.

Two not-so-nice ways

1) modify source() so it does something like


    magic.command<-function() get(".Last.source.file",envir=.GlobalEnv)

2) Get the file name from the environment inside source

	get("file", parent.frame(n-1)

The problem with the first is that it writes in the global workspace and
that it fails if a source()d file source()s another file before you use

The problem with the second is that it will break if the source() function is
renamed or if the name of the variable "file" changes.

You also need to be aware that `file' need not be a filename. It could be
a URL [eg source("http://www.bioconductor.org/getBioC.R") ] or a
connection (either a file connection or some other sort).


r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list