Function to apply arbitrary functions in R
How would one implement in R the function apply.func(func, arg.list)
, which takes an arbitrary function func
and a suitable list arg.list
as arguments, and returns the result of calling func
with the argum开发者_开发百科ents contained in arg.list
. E.g.
apply.func(foo, list(x="A", y=1, z=TRUE))
is equivalent to
foo(x="A", y=1, z=TRUE)
Thanks!
P.S. FWIW, the Python equivalent of apply.func
would be something like
def apply_func(func, arg_list):
return func(*arg_list)
or
def apply_func(func, kwarg_dict):
return func(**kwarg_dict)
or some variant thereof.
I think do.call
is what you're looking for. You can read about it via ?do.call
.
The classic example of how folks use do.call
is to rbind
data frames or matrices together:
d1 <- data.frame(x = 1:5,y = letters[1:5])
d2 <- data.frame(x = 6:10,y = letters[6:10])
do.call(rbind,list(d1,d2))
Here's another fairly trivial example using sum
:
do.call(sum,list(1:5,runif(10)))
R allows functions to be passed as arguments to functions. This means you can define apply.func
as follows (where f
is a function and ...
indicates all other parameters:
apply.func <- function(f, ...)f(...)
You can then use apply.func
to and specify any function where the parameters makes sense:
apply.func(paste, 1, 2, 3)
[1] "1 2 3"
apply.func(sum, 1, 2, 3)
[1] 6
However, note that the following may not produce the results you expected, since mean
takes a vector as an argument:
apply.func(mean, 1, 2, 3)
[1] 1
Note that there is also a base R function called do.call
which effectively does the same thing.
精彩评论