[Rd] Can a function know what other function called it?

Kynn Jones kynnjo at gmail.com
Sat May 23 23:50:11 CEST 2009


On Sat, May 23, 2009 at 4:55 PM, Robert Gentleman <rgentlem at fhcrc.org> wrote:
> Hi Kynn,
>
>
> Kynn Jones wrote:
>> Suppose function foo calls function bar.  Is there any way in which
>> bar can find out the name of the function that called it, "foo"?
>
>  essentially yes. You can find out about the call stack by using sys.calls and
> sys.parents etc. The man page plus additional manuals should be sufficient, but
> let us know if there are things that are not clear.

Thanks a lot!  That was very helpful.

This is the best I was able to come up with:

bar <- function() {
  caller <- sub("\\(.*", "", rev(sys.calls())[[2]])
  cat(sprintf("bar: i was called by \"%s\"\n", caller))
}

foo <- function() bar()

> foo()
bar: i was called by "foo"
>

So it works, but I'm a n00b with R.  If there's a less labored way to
achieve this, please let me know.

And thanks again for your response.  It was very instructive.

KJ



More information about the R-devel mailing list