Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to apply arbitrary functions in R

Tags:

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 arguments 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.

like image 261
kjo Avatar asked May 31 '11 18:05

kjo


People also ask

Can you put a function inside a function in R?

A nested function or the enclosing function is a function that is defined within another function. In simpler words, a nested function is a function in another function. There are two ways to create a nested function in the R programming language: Calling a function within another function we created.

Can functions take another function as an argument in R?

14.1 Functions in RFunctions can be passed as arguments to other functions. This is very handy for the various apply functions, like lapply() and sapply() . Functions can be nested, so that you can define a function inside of another function.

What is the use of options () function in R?

The options() function in R is used to set and examine different global options that affects the way in which R determines and returns its results.


1 Answers

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)))
like image 50
joran Avatar answered Sep 26 '22 03:09

joran