Search code examples
rnumerical-integrationintegral

Evaluating an integral in R multiple times


I am trying to integrate the next function with respect x

integrand <- function(x) {
f1 <- pnorm((1/sqrt(u/x))*( sqrt((t*u*v)/x) - sqrt(x/(t*u*v)) ))}

where,

v=10
u=5

However, I need to integrate considering different values of t, so tried defining a sequence of values as:

t=seq(0,100,0.1)

And used the sapply function as:

data=sapply(t, function(x) integrate(integrand, lower = 0 , upper = 10000)$value )

I got these errors:

    Error in integrate(integrand, lower = 0, upper = 10000) : 
  evaluation of function gave a result of wrong length
In addition: Warning messages:
1: In (t * u * v)/x : longer object length is not a multiple of shorter object length
2: In x/(t * u * v) : longer object length is not a multiple of shorter object length
3: In (1/sqrt(u/x)) * (sqrt((t * u * v)/x) - sqrt(x/(t * u * v))) :
  longer object length is not a multiple of shorter object length

I haven't had any luck.

I would greatly appreciate any help.

Regards!


Solution

  • You can still use sapply like so:

    sapply(t, function(t) {
      integrate(function(x) {
        pnorm((1/sqrt(u/x))*( sqrt((t*u*v)/x) - sqrt(x/(t*u*v)) ))
      }, lower = 0, upper = 1000)$value
    })
    

    Output

    [1]  0.000000  5.416577 10.251273 15.146418 20.084907 25.049283 ...