Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: how to pass functions as arguments to another function

Tags:

r

Suppose I want to integrate some function that involves sums and products of a few other user defined functions. Lets take an extremely simple example, it gives the same error.

integrate(f = sin + cos, lower=0, upper=1)

This yields "Error in sin + cos : non-numeric argument to binary operator" which I think is saying it doesn't make sense to just add functions together without passing them some sort of argument. So I am a bit stuck here. This thread poses what I think is a solution to a more complicated question, that can be applied here, but it seems long for such a simple task in this case. I'm actually kind of surprised that I am unable to find passing function arguments to functions in the help manual so I think I am not using the right terminology.

like image 914
WetlabStudent Avatar asked Jul 19 '13 20:07

WetlabStudent


People also ask

How do you pass a function as a parameter in another function in R?

Adding Arguments in R We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis. Below is an implementation of a function with a single argument.

Can you pass a 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.

How can we pass a function name as an argument to another function?

To pass a function as an argument to another function, write the name of the function without parenthesis in the function call statement (just like what we do with variables) and accept the reference of the function as a parameter in the called function.

Can you pass a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions.


1 Answers

Just write your own function:

> integrate(f = function(x) sin(x) + cos(x), lower=0, upper=1)
1.301169 with absolute error < 1.4e-14

In this example I've used an anonymous function, but that's not necessary. The key is to write a function that represents whatever function you want to integrate over. In this case, the function should take a vector input and add the sin and cos of each element.

Equivalently, we could have done:

foo <- function(x){
    sin(x) + cos(x)
}
integrate(f = foo, lower=0, upper=1)
like image 67
joran Avatar answered Oct 13 '22 18:10

joran