Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading