Lin
Lin

Reputation: 195

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!

Upvotes: 5

Views: 10220

Answers (2)

mt1022
mt1022

Reputation: 17299

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.

Upvotes: 9

dayne
dayne

Reputation: 7784

Another illustration of the solution:

integrate(function(x) rep(1, length(x)), 0, 1)

Upvotes: 0

Related Questions