Is this what you want?

myf<-function(FUN, x){
            res<- vector( mode="list")
            for(i in FUN)
                        res[[i]]<-do.call(i,args=list(x))
            return(res)
}

 > myf(FUN="mean",x=1:10)
 > myf(FUN=c("mean","max"),x=1:10)
 > myf(FUN=c("mean","max", "sum", "median"),x=1:10)




Ales Ziberna wrote:

>Dear useRs?
>
>
>
>I have the following problem! I have a function that calls one or more 
>functions, depending on the input parameters. I am searching for the fastest 
>way to select and execute the selected functions and return their results in 
>a list. The number of possible functions is 10, however usually only 2 are 
>selected (although sometimes more, even all).
>
>
>
>For examples, if I have function "myf" and the possible functions that I 
>want to call are "mean", "max" and "sum". I have thought of one way (myf) to 
>do that and am interested if there maybe exists a faster way (the speed is 
>very important, since this can be repeated millions of times in my 
>function).
>
>
>
>
>
>myf<-function(FUN, x){
>
>            f<-list(mean=mean, max=max, sum=sum)
>
>            res<- vector( mode="list")
>
>            for(i in FUN){
>
>                        res[[i]]<-f[[i]](x)
>
>            }
>
>            return(res)
>
>}
>
>myf(FUN=c("mean","max"),x=1:10)
>
>
>
>
>
>In this case, it would be faster if I would compute all functions, even if I 
>need only one:
>
>myf.all<-function(x){
>
>            list(mean=mean(x), max=max(x), sum=sum(x))
>
>}
>
>
>
>  
>
>>gc();system.time(for(i in 1:10000)myf.all(1:20))
>>    
>>
>
>         used (Mb) gc trigger (Mb) max used (Mb)
>
>Ncells 165659  4.5     350000  9.4   350000  9.4
>
>Vcells  61135  0.5     786432  6.0   283043  2.2
>
>[1] 0.90 0.00 1.08   NA   NA
>
>  
>
>>gc();system.time(for(i in 1:10000)myf(FUN="mean",1:20))
>>    
>>
>
>         used (Mb) gc trigger (Mb) max used (Mb)
>
>Ncells 165659  4.5     350000  9.4   350000  9.4
>
>Vcells  61135  0.5     786432  6.0   283043  2.2
>
>[1] 1.14 0.00 1.40   NA   NA
>
>
>
>This does (usually) not happen in my case, since most of functions I 
>consider are more complex.
>
>
>
>Thanks in advance for any suggestions!
>
>
>Best regards,
>
>Ales Ziberna
>
>______________________________________________
>[email protected] mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>  
>


-- 
Ferdinand Alimadhi
Programmer / Analyst
Harvard University
The Institute for Quantitative Social Science
(617) 496-0187
[EMAIL PROTECTED]
www.iq.harvard.edu


        [[alternative HTML version deleted]]

______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to