简体   繁体   中英

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!

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 ...

A previous post have a similar problem with an specific solution here

the code would result as:

t=seq(0,100,0.1)
fu<- list()
int<- numeric()
for(i in 1:length(t))
  {
    fu[[i]] = function(x){
    f1 <- pnorm((1/sqrt(u/x))*( sqrt((t[i]*u*v)/x) - sqrt(x/(t[i]*u*v)) ));
  }
    int[i] = integrate(h[[i]], lower=0, upper=1000)$value
  }
  int

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