Martin Doumen - 3 months ago 22
R Question

# R summation within integration

I'm trying to figure out how to integrate the following function in R:

``````item.fill.rate <- function(x, lt, ib, S){
1-((((1/(factorial(S)))*((x*lt*ib)^S)))/
(sum(((1/(factorial(0:S)))*((x*lt*ib)^(0:S))))))}
``````

Where x is a variable and lt, ib and S are input parameters

Based on a previous topic on here, I tried the following:

``````int.func <- function(lt, ib, S){
item.fill.rate <- function(x){
1-((((1/(factorial(S)))*((x*lt*ib)^S)))/(sum(((1/(factorial(0:S)))*((x*lt*ib)^(0:S))))))
}
return(item.fill.rate)
}
integrate(int.func(0.25, 1, 1), lower=0.25, upper=0.75)\$value
``````

When applying this, I get the following error:

``````> integrate(int.func(0.25, 1, 1), lower=0.25, upper=0.75)\$value
[1] 0.4947184
Warning messages:
1: In (x * lt * ib)^(0:S) :
longer object length is not a multiple of shorter object length
2: In (1/(factorial(0:S))) * ((x * lt * ib)^(0:S)) :
longer object length is not a multiple of shorter object length
``````

I evaluated the length of those objects, but that did not give me any indication where the error must be.

I tried to be as specific as possible, so hopefully someone is able to help me out with this!

The `sum` function is notorious for returning single items when a longer vector was expected, so integrand functions that have a call to `sum` generally need to be "vectorized" so they deliver the expected results (a vector of the the same length as a provided "x"-vector) for `integrate` to succeed. The Vectorize function is a wrapper for `sapply` and is quite handy for this process. You can set the parameters in the call to `integrate`. (At the moment I think you may be integrating a constant over a domain of length 1/2.)
``````item.fill.rate <- function(x,lt, ib, S){