R – help making function not vectorized for use with pracma package and calculation of infinite integrals

I have the following R code:

beta <- 3.2
sigma <- 1.2
mu <- beta - tau

integrand <- function(Ti){
  r <- Ti*dlnorm(x = Ti, meanlog = mu, sd = sigma)
  return(r)
}

tau <- -5:5

quadinf(integrand, 0, Inf)$Q

I am trying to calculate the integral as shown in the code using the quadinf function from the pracma package, however, I am getting the following error:

Error in if (delta < tol) break : the condition has length > 1

In the documentation of the quadinf function it says:

The integrand function needs not be vectorized.

So I am assuming that the error could be connected to my integrand function being vectorized? But then how can I make it not vectorized? Or is the problem somewhere else?

>Solution :

We may use a for loop here as the tau vector is of length greater than 1, and thus the dlnorm returns length > 1

out <- numeric(length(tau))
for(i in seq_along(tau)) {
        mu <- beta - tau[i]
        out[i] <- quadinf(integrand, 0, Inf)$Q
   }

-output

> out
 [1] 7480.0892297 2751.7710457 1012.3199945  372.4117139  137.0026132   50.4004448   18.5412875    6.8209585    2.5092904    0.9231163    0.3395955

Leave a Reply