[R] Determining name of calling function.
Peter Dalgaard
P.Dalgaard at biostat.ku.dk
Mon Sep 28 16:57:48 CEST 2009
(Oops, that was of course intended for Rolf, not Baptiste)
Peter Dalgaard wrote:
> baptiste auguie wrote:
>> Not answering your question, but just pointing out the example of
>>
>> base::.NotYetImplemented()
>>
>> essentially doing the same thing.
>>
>> Best,
>>
>> baptiste
>>
>>
>> 2009/9/28 Rolf Turner <r.turner at auckland.ac.nz>:
>>> 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
>>>
>
> (How old are you? Surely you are aware that avuncular advice usually
> comes from your parents' siblings and their spouses.)
>
> I'd maybe be more inclined to use something like
> deparse(sys.call(-1)[[1]]) but there's no clear benefit.
>
> The main trap would be that the first element of the call is not
> necessarily a name. Consider
>
>> (function(x)deparse(sys.call()[[1]]))(x=2)
> [1] "(function(x) deparse(sys.call()[[1]]))"
>> (function(x)as.character(sys.call()[1]))(x=2)
> [1] "(function(x) as.character(sys.call()[1]))"
>
> and notice that in fact the function bing called may not even _have_ a name.
>
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list