[R] function question

Peter Dalgaard p.dalgaard at biostat.ku.dk
Thu Mar 19 19:54:14 CET 2009


Patrick Burns wrote:
> Duncan Murdoch wrote:
>> On 3/19/2009 12:49 PM, Edna Bell wrote:
>>> Dear R Gurus:
>>>
>>> I read somewhere that functions are considered vectors.
>>>
>>> Is this true, please?
>>
>> Your question is a little ambiguous (you probably did read that, and 
>> probably someone does consider them to be vectors), but I think the 
>> right answer is no:  when the R documentation talks about vectors, it 
>> is not talking about functions, and the is.vector() function returns 
>> FALSE for functions.
>>
>> Duncan Murdoch
> 
> It could be that you read that about S+ functions,
> where they can be thought of as (very special)
> vectors.  R functions are different in this respect.

Yes. Not that different though. You can't do e.g. mean[[1]] as you can in S:
 > mean[[1]]
Error in mean[[1]] : object of type 'closure' is not subsettable

However, also in R, functions can be converted to and from generic 
vectors (i.e., lists) using as.list/as.function. The last element in the 
list form is the function body, the others are the default argument list.

 > mn <- as.list(mean)
 > names(mn)[1]<-"foo"
 > as.function(mn)
function (foo, ...)
UseMethod("mean")
 > mn
$foo


$...


[[3]]
UseMethod("mean")


(Notice that this is mainly a mechanism to allow porting of sneaky S 
codes. In R, you'd more likely do it with formals() and body() and their 
assignment forms.)


-- 
    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