简体   繁体   中英

R: how to pass functions as arguments to another function

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.

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)

This is an old question, but I recently struggled with it, so here is a simple example in case it helps others in the future. @joran's answer is still the best.

Define your first function: f1 <- function(x){return(x*2)}

Test it: f1(8) (expect 8*2=16); returns [1] 16

Define your second function: f2 <-function(f, y){return(f+y)}

Test it: f2(f=f1(8), y=1) (expect 8*2 = 16 +1 = 17); returns [1] 17

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM