[R] tapply and more than one function, with different arguments

RINNER Heinrich HEINRICH.RINNER at tirol.gv.at
Tue Jan 26 17:26:10 CET 2010


Dear R-users,

I am working with R version 2.10.1.

Say I have is a simple function like this:

> my.fun <- function(x, mult) mult*sum(x)

Now, I want to apply this function along with some other (say 'max') to a simple data.frame, like:

> dat <- data.frame(x = 1:4, grp = c("a","a","b","b"))

Ideally, the result would look something like this (if mult = 10):
  max my.fun
a   2     30
b   4     70

I have tried it that way:

apply.more.functions <- function(dat, FUN = c("max", "my.fun"), ...) {
  res <- NULL
  for(f in FUN) res[[f]] <- tapply(dat$x, dat$grp, FUN = f, ...)
  data.frame(res)
}

# let's test it:
> apply.more.functions(dat, FUN = c("max", "min"))
  max min
a   2   1
b   4   3
# perfect!

# now, with an additional argument:
> apply.more.functions(dat, FUN = c("max", "my.fun"), mult = 10)
  max my.fun
a  10     30
b  10     70
# uhuh!
Apparently, 'mult' has been used in the calculation of 'max' as well.
How can I modify apply.more.functions in order to avoid this?

Your advice would be appreciated;
Kind regards
Heinrich.



More information about the R-help mailing list