[R] Determining name of calling function.

Gabor Grothendieck ggrothendieck at gmail.com
Mon Sep 28 01:34:57 CEST 2009


Not sure if this is important to you but R functions don't have to
have names so what you get back won't be a name if the function was
anonymous.  In the example below an anonymous function calls fname and
the returned string is the calling sequence but that's not its name
since it has no name.  In fact, in a sense no R functions have names.
You can store them in variables and call that variable its "name" but
that is not an intrinsic part of the function itself.  A function is
just an environment, an argument list and a body -- no name.

> fname <- function() as.character(sys.call(-1))[1]
> (function() fname())()
[1] "(function() fname())"


On Sun, Sep 27, 2009 at 7:24 PM, Rolf Turner <r.turner at auckland.ac.nz> wrote:
>
> I have vague recollections of seeing this question discussed on r-help
> previously, but I can't find the relevant postings.
>
> I want to determine (from within a given function) the name of the function
> calling that given function.
>
> E.g. if I have a function foo() which calls a function bar(), and also
> a function clyde() which calls bar(), I want to have, in the code of bar(),
> an instruction which will return the character string "foo" if bar() was
> called from foo() and the string "clyde" if bar() was called from clyde().
>
> Without really understanding what I'm doing I cobbled together the
> following:
>
> fname <- as.character(sys.call(-1))[1]
>
> This ***seems*** to work, at least in simple test cases.
>
> But is it reliably robust?  Are there traps for young players that I am
> not seeing?
>
> My ``solution'' returns NA as the value of fname if bar() is called from the
> command line, rather than being called by foo() or clyde().  This is
> acceptable.
> I think ....
>
> Any avuncular advice from those younger and wiser than myself? :-)
>
>        cheers,
>
>                Rolf Turner
>
> ######################################################################
> Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list