From kynnjo at gmail.com  Sat May 23 23:50:11 2009
From: kynnjo at gmail.com (Kynn Jones)
Date: Sat, 23 May 2009 17:50:11 -0400
Subject: [Rd] Can a function know what other function called it?
In-Reply-To: <4A1862AD.2070600@fhcrc.org>
References: <c2350ba40905231337u5ead6f97o95ee24f2faea081e@mail.gmail.com>
	<4A1862AD.2070600@fhcrc.org>
Message-ID: <c2350ba40905231450x344bb6f6j748d5a18c4af41b9@mail.gmail.com>

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



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