6

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.

2 Answers 2

8

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)
Sign up to request clarification or add additional context in comments.

1 Comment

That is to say, what you want to add together (mathematically) is the result of the function (sin(x) and cos(x)), not the functions themselves.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.