Search code examples
rintegration

Error in integrate : evaluation of function gave a result of wrong length


Try the code below:

library(pracma)

f <- function(x) 1

integrate(f,0,1)$value
quad(f,0,1)

quad() works correctly but integrate() reports the error message:

Error in integrate(f, 0, 1) : evaluation of function gave a result of wrong length

What is wrong with this integrate() application? Thanks in advance!


Solution

  • You can try:

    integrate(Vectorize(f),0,1)$value
    

    see the manual of integrate: f should be an R function taking a numeric first argument and returning a numeric vector of the same length. Vectorize will make f a such function that returns an output of the same length as input.