[R] Evaluate a function for various value of parameters
Gabor Grothendieck
ggrothendieck at myway.com
Sat Oct 23 04:40:58 CEST 2004
Gabor Grothendieck <ggrothendieck <at> myway.com> writes:
:
: Stephane DRAY <dray <at> biomserv.univ-lyon1.fr> writes:
: : I would like to create a function "evaluatemyfunction" which evaluate a
: : function f for different values of parameters. For instance, if
: : f=function(a,b) a*b
: : evaluatemyfunction(f,1:10,5) would return:
: : 5
: : 10
: : 15...
: :
:
: This is not a general solution (Olaf has already provided that) but
: in some cases you may simply be able to write your function f so that
: it takes vector arguments. For example, with the f you have above
: one could write f(1:10,5) .
Sorry, I missed the last part of your question where you
provided some code. That code shows that you want all
combos, not just parallel evaluation of the args so here
it is again.
This answer creates a grid and evaluates. It makes use of
do.call and mapply.
The first two lines of the body collect the args into a list and
create the grid. The third line reestablishes the names of the
columns since expand.grid may not give the ones we want.
Lastly we preface the grid with the function name and mapply
the result.
evaluatemyfunction <- function(f, ...) {
args <- list(...)
grid <- do.call("expand.grid", args)
names(grid) <- names(args)
do.call("mapply", append("f", grid))
}
More information about the R-help
mailing list