[R] How do I obtain the current active path of a function that's being called?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 6 12:52:14 CEST 2012


On Tue, Jun 5, 2012 at 4:58 PM, Michael <comtech.usa at gmail.com> wrote:
> Hi all,
>
> How do I obtain the current active path of a function that's being called?
>
> That's to say, I have several source files and they all contain definition
> of function A.
>
> I would like to figure out which function A and from which file is the one
> that's being called and is currently active?
>

Here are a few possibilities:

1. In each source file add this line:

this.file <- sys.frame(1)$ofile

Then if you do this:

source("a.R")

the variable this.file will be left in your global environment so you
can find out what your last file read in was.

A slightly more sophisticated version creates a stack of file names:

if (!exists("this.file")) this.file <- NULL
this.file <- unique(c(sys.frame(1)$ofile, this.file))

This is a bit of a hack.  If the internals of source change then  you
will have to change this code in a corresponding manner.

2. source each file into a separate environment.

source("a.R", local = a <- new.env(parent = .GlobalEnv))
# if f is a function in a.R then call it like this:
a$f(...whatever...)

Be sure you source each file into a different environment.

3. In the source file a.R write each function like this:

f <- function()
# a.R
{
...whatever...
}

Then as.character(attr(f, "srcfile"))[2] will show the comment.  Be
sure that getOption("keep.source") is TRUE (normally it is) or if its
not feasible to arrange that then set it in each source call:

source("a.R", keep.source = TRUE)

4. put your functions in packages.  search() will show the packages
you have loaded in order.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list