[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

 	source("/path/name/filename.r",chdir=TRUE)

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

    assign(".Last.source.file",file,envir=.GlobalEnv)

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


2) Get the file name from the environment inside source

     magic.command<-function(){
	n<-match("source",rev(as.character(sapply(sys.calls(),"[[",1))))
	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
magic.command().

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


	-thomas

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