Home > Blockchain >  Integration Error: length(lower) == 1 is not TRUE
Integration Error: length(lower) == 1 is not TRUE

Time:06-10

I am trying to numerically integrate a probability distribution over a range of values. This should look something like this. For example, I would like to do this with the Exponential Probability Distribution Function (https://en.wikipedia.org/wiki/Exponential_distribution, http://homepages.math.uic.edu/~jyang06/stat401/handouts/handout8.pdf):

## define the integrated function (for lambda = 2)

integrand <- function(x) {2 * 2.718^(-2*x)}

upper = seq(0, 5, by = 0.01)
lower = 0

data = data.frame(lower,upper)
data$integral = integrate(integrand, lower = data$lower, upper = data$upper)

Unfortunately, I got this error:

Error in integrate(integrand, lower = my_data$lower, upper = my_data$upper) : 
  length(lower) == 1 is not TRUE
  • Does anyone know what this means and how I can avoid it?

This is strange because the integrate function works normally otherwise:

> integrate(integrand, lower = 0, upper = 0.01)
0.02020132 with absolute error < 2.2e-16

> integrate(integrand, lower = 0, upper = 0.06)
0.127496 with absolute error < 1.4e-15

Thank you!

CodePudding user response:

Try this

data$integral  <- apply(data, 1, function(x) {integrate(integrand, lower = x[1], upper = x[2])$value})

head(data)
  lower upper   integral
1     0  0.00 0.00000000
2     0  0.01 0.02020132
3     0  0.02 0.04081069
4     0  0.03 0.06183635
5     0  0.04 0.08328672
6     0  0.05 0.10517036
  •  Tags:  
  • r
  • Related