R: Error in Integration with Vector Function and Its Remedy

This post illustrates how to address an error arising from the integration of one of the results of a vector function in R. A straightforward remedy is to use Vectorize().




R Integration with a Single Element from a Vector Function



The Integration in R is simple and straightforward, as follows:

func1 <- function(x) {
    return(x*x)
}
 
integrate(func1,lower=5, upper=0)$value
 
# result ; works well
> integrate(func1,lower=5, upper=0)$value
[1-41.66667
 
cs


I used a vector function, which is also employed in another part of the code for computing function values. To eliminate redundancy, I employ this vector function even when integration is required.

However, I encountered an unexpected error when using a single entry of the vector function as an integrand, as shown below.

# vector function
vec_func <- function(x) {
    col1 <- x
    col2 <- exp(-2*x)
    ret <- cbind(col1, col2)
    return(ret)
}
 
wrapper_func <- function(x) { 
 
    # Reuse the vector function
    B <- vec_func(x)
    
    # the same result as the func1()
    ret <- B[1]*B[1]
    return(ret)
}
 
integrate(wrapper_func,lower=5, upper=0)$value
 
> # does not work
> integrate(wrapper_func,lower=5, upper=0)$value
Error in integrate(wrapper_func, lower = 5, upper = 0) : 
evaluation of function gave a result of wrong length
 
cs


Google presented a solution to this error, suggesting the use of the Vectorize() function, as demonstrated below.

integrate(Vectorize(wrapper_func), lower=5, upper=0)$value
 
> # does work
> integrate(Vectorize(wrapper_func), lower=5, upper=0)$value
[1-41.66667
 
cs


I'm not entirely certain why this solution works. My suspicion is that vector operations affect the integration process. As long as the answer is correct exactly, I simply accept it as a rule within R since it is a technical issue.

No comments:

Post a Comment