Reputation: 5925
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
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!
Upvotes: 1
Views: 1166
Reputation: 53
Just in case anyone ran into a similar problem that I had with this error... I was trying to run an integrate function on my data:
sei <- function(t = 1) exp(-t)/t # standard exponential integral
alpha <- vegan::fisherfit(data)$estimate # alpha estimate
N <- sum(data) # number of observations
rank.logseries <- sapply(data, function(x) {
logeqn <- x * log(1 + alpha/N)
f<-integrate(sei, logeqn, Inf)
fv<-f[["value"]]
alpha*fv
})
And I got the same error. I realized the issue was my data was a single column dataframe. Once I clarified this, the integrate worked perfectly.
sei <- function(t = 1) exp(-t)/t # standard exponential integral
alpha <- vegan::fisherfit(data)$estimate # alpha estimate
N <- sum(data) # number of observations
rank.logseries <- sapply(data[,1], function(x) {
logeqn <- x * log(1 + alpha/N)
f<-integrate(sei, logeqn, Inf)
fv<-f[["value"]]
alpha*fv
})
Upvotes: 1
Reputation: 15143
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
Upvotes: 1