[R] Re ading Functions that are in a Vector

David Winsemius dwinsemius at comcast.net
Mon Sep 28 05:30:33 CEST 2009


On Sep 27, 2009, at 11:07 PM, Rolf Turner wrote:

>
> On 28/09/2009, at 3:36 PM, trumpetsaz wrote:
>
>>
>> I am trying to write a function that will have an input of a vector  
>> of
>> functions. Here is a simplistic example.
>> sumstats <- c(mean,sd)
>> sumstats[1]
>> #Gives this error
>> #> sumstats[1]
>> #[[1]]
>> #function (x, ...)
>> #UseMethod("mean")
>> #<environment: namespace:base>
>>
>> I thought about restricting the input to character variables such  
>> as the
>> following
>> sumstats2 <- c("mean","sd")
>> Is there a way to change "mean" to the function mean?
>
> You *can't* have a vector of functions, as far I know.  The entries
> of a vector must be (numeric, character, or logical) scalars.
>
> You *can* have a *list* of functions; this might be the way you
> want to go.
>
> To ``change "mean" to the function mean'' --- set ?get.
>

That is prezactly what he created:

 > umstats <- c(mean,sd)
 >
 > str(umstats)
List of 2
  $ :function (x, ...)
  $ :function (x, na.rm = FALSE)


And what's more "it works" if it is accessed with "[[":

 > umstats[[1]](c(1,2,3,4,5))
[1] 3



David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list