Function for applying arbitrary functions to R

How to implement the function apply.func(func, arg.list) in R, which takes an arbitrary function func and a suitable list arg.list as arguments and returns the result of calling func with the arguments contained in arg.list , for example.

 apply.func(foo, list(x="A", y=1, z=TRUE)) 

equivalently

 foo(x="A", y=1, z=TRUE) 

Thanks!

PS FWIW, Python's equivalent apply.func will be similar to

 def apply_func(func, arg_list): return func(*arg_list) 

or

 def apply_func(func, kwarg_dict): return func(**kwarg_dict) 

or its variant.

+7
source share
2 answers

I think do.call is what you are looking for. You can read about it through ?do.call .

A classic example of how people use do.call is in 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 is another pretty trivial example using sum :

 do.call(sum,list(1:5,runif(10))) 
+17
source

R allows you to pass functions as arguments to functions. This means that you can define apply.func as follows (where f is a function, and ... are all other parameters:

 apply.func <- function(f, ...)f(...) 

Then you can use apply.func to and specify any function where the parameters make 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 expected results, since mean takes a vector as an argument:

 apply.func(mean, 1, 2, 3) [1] 1 

Note that there is also a basic R function called do.call that actually does the same thing.

+8
source

All Articles