[R] Applying multiple functions to one object

Karl Ove Hufthammer karl at huftis.org
Fri Feb 4 09:40:06 CET 2011


Eik Vettorazzi wrote:

> ... and so the following is from scratch, not from memory.
> 
> fun<-function(x,...){
> mthd<-list(...)
> lapply(mthd,function(m) do.call(m,list(x)))
> }
> fun(3.14, mode, typeof, class)
> 
> there is no error-catching for non-existing functions, no naming of
> results and so on, but it may be a start.

Thanks for the suggestion. I took the liberty of adding function names and
support for multiple objects. Here’s the resulting function (‘msum’ is
short for ‘multiple summaries’, or something like that …):

msum = function(x,...){
  fun.names = sapply(lapply(substitute(list(...)), deparse)[-1], paste, collapse="")
  mthd<-list(...)
  if(!is.list(x)) x = list(x)
  res = t(sapply(x, function(y) sapply(mthd, function(m) do.call(m, list(y)) )))
  colnames(res) = fun.names
  rownames(res) = names(x)
  res
}

It works for simple objects:

$ msum( rnorm(100, 2, 3), mean, median, sd, mad)
         mean   median       sd      mad
[1,] 2.380686 2.410399 3.073316 3.034474

For multiple objects:

$ x = list(3, 3L, 3.14, factor(3), "3")
$ msum(x, mode, typeof, class)
     mode        typeof      class      
[1,] "numeric"   "double"    "numeric"  
[2,] "numeric"   "integer"   "integer"  
[3,] "numeric"   "double"    "numeric"  
[4,] "numeric"   "integer"   "factor"   
[5,] "character" "character" "character"

And it adds row names if they are specified:

$ x = list(norm=rnorm(100), exp=rexp(100), gamma=rgamma(100, 3, 5))
$ msum(x, mean, median )
            mean     median
norm  -0.1539711 -0.1048998
exp    0.9726821  0.7661752
gamma  0.5556737  0.4678005

Hope someone else will find it useful too.

-- 
Karl Ove Hufthammer



More information about the R-help mailing list