[R] Handling functions as objects

David Winsemius dwinsemius at comcast.net
Thu Mar 29 19:43:08 CEST 2012


On Mar 29, 2012, at 1:34 PM, Duncan Murdoch wrote:

> On 29/03/2012 1:02 PM, Julio Sergio wrote:
>> I learnt that functions can be handled as objects, the same way the  
>> variables
>> are. So, the following is perfectly valid:
>>
>> >  f = function(a, b) {
>> +    print(a)
>> +    print(b)
>> + }
>> >
>> >  f1 = function(foo) {
>> +    foo(1,2)
>> + }
>> >
>> >  f1(f)
>> [1] 1
>> [1] 2
>> >
>>
>> I also know that operators are functions, so, I can call:
>>
>> >  '+'(1,2)
>> [1] 3
>> >
>>
>> However, when I want to pass the '+' function to the previous f1  
>> function, it
>> doesn't work:
>>
>> >  f1('+')
>> Error en f1("+") : no se pudo encontrar la función "foo"
>> >
>>
>> (Error in f1("+") : the function "foo" cannot be found)
>>
>> Do you have any comments on this?
>
> You are seeing the effects of the evaluator and parser being  
> helpful.  When you say
>
> foo(1,2)
>
> the evaluator looks for an object that appears to be a function and  
> evaluates it.  Since foo is a character vector in your last example,  
> it skips over that one, and never finds another.
>
> When you say
>
> '+'(1,2)
>
> the parser sees a string constant being used in a context where a  
> function name is needed, so it helpfully converts it to an object  
> name, and then the evaluator looks up that name, and finds the  
> addition function.
>
> You can get the results you want by using f1(`+`), i.e. being  
> explicit about passing the name of the addition function.  If you  
> have a string containing a function name, you need to explicitly use  
> get() to retrieve it.  Use get(foo, mode="function") to skip over  
> non-functions.

There is also the `do.call` function to construct proper calls from a  
character that matches the name of a function

  f1 = function(foo) {
      do.call(foo, list(1,2))
   }

  f1("+")
[1] 3

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list