2

I am using integrate function (in R) to numerically compute integrals. I have an univariate function with one argument f(x,a) like this (just for example purpose):

test = function(x,a) 1/sqrt(2*pi)*exp(-(x-a)^2/2)

I want to define new univariate function, which is a function of a after integrate the above function:

testa = function(a) integrate(test,0,Inf,a=a)$value #this works

Now my question is that is it possible to use integrate function on function testa ? For example:

integrate(testa,0,1) # not working

I tried and it is not working (got error message evaluation of function gave a result of wrong length). I already know that one can apply multivariate integration procedure directly on test (for example use adaptIntegrate function from cubature package). But that is not my purpose!

So does anyone know how to apply successively integrate function like the example above? Or confirm that this is not permitted in R?

Thank in advance

Tuan
  • 41
  • 2

1 Answers1

3

integrate needs a vectorized function. You can use Vectorize:

integrate(Vectorize(testa),0,1)
#0.6843731905 with absolute error < 0.00000000000022

Disclaimer: I haven't checked the result for correctness.

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Waoh this works! and thanks for your rapid answer! By the way, could you please explain the mechanism behind `Vectorize(testa)`. I also tried, for instance, `testa = function(a) integrate(Vectorize(test,vectorize.args='x',0,Inf,a =a )$value ` but it is not working. Thanks – Tuan Mar 03 '14 at 11:00
  • 1
    `test` is already vectorized in x. There is no need to use `Vectorize` there. `help("Vectorize")` explains how it works. – Roland Mar 03 '14 at 11:48