5

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!

Lin
  • 195
  • 1
  • 12

2 Answers2

8

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.

mt1022
  • 16,834
  • 5
  • 48
  • 71
0

Another illustration of the solution:

integrate(function(x) rep(1, length(x)), 0, 1)
dayne
  • 7,504
  • 6
  • 38
  • 56