[R] tapply and more than one function, with different arguments
RINNER Heinrich
HEINRICH.RINNER at tirol.gv.at
Tue Jan 26 21:25:32 CET 2010
Hi Dennis,
now that's a very nice function, and this seems to be just what I need!
Thanks a lot!
-Heinrich.
________________________________________
Von: Dennis Murphy [djmuser at gmail.com]
Gesendet: Dienstag, 26. Januar 2010 19:44
An: RINNER Heinrich
Cc: r-help
Betreff: Re: [R] tapply and more than one function, with different arguments
Hi:
Using the plyr package, we can get the result as follows:
> library(plyr)
> my.fun <- function(x, mult) mult*sum(x)
> dat <- data.frame(x = 1:4, grp = c("a","a","b","b"))
> ddply(dat, .(grp), summarize, max = max(x), myfun = my.fun(x, 10))
grp max myfun
1 a 2 30
2 b 4 70
HTH,
Dennis
On Tue, Jan 26, 2010 at 8:26 AM, RINNER Heinrich <HEINRICH.RINNER at tirol.gv.at<mailto:HEINRICH.RINNER at tirol.gv.at>> wrote:
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.
______________________________________________
R-help at r-project.org<mailto:R-help at r-project.org> mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list