Numerical Integration in R

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 (Exponential distribution - Wikipedia,

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


is 501,
i.e. you are asking it to use 501 lower bounds and it doesnt know what to do.
unlike in your hand picked example where you say lower should be 0

1 Like

Thank you for your answer! I tried to change 501 to 500:

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

But now I get a new error:

data = data.frame(lower,upper)
Error in data.frame(lower, upper) :
arguments imply differing number of rows: 500, 501

Is this what you had in mind?


No... why do you feel the need to have lower in data ? You already have it in a named variable, lower

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.