[R] integrate() function error

andrew andrewjohnroyal at gmail.com
Fri Oct 23 04:29:49 CEST 2009

Change e2 to the following and it works

e2 <- function(a) a^2/2

The reason it doesn't is that e2 must be able to handle vector inputs
correctly.   Your original function does not do this.

from ?integrate

f - an R function taking a numeric first argument and returning a
numeric vector of the same length. Returning a non-finite element will
generate an error.

You could change it to the following

e2 <- function(x) { out <- 0*x; for(n in 1:length(x)) out[n] <-
integrate(function(y) y,lower=0,upper=x[n])$value; out }

and it seems to give the correct answer for me.

On Oct 23, 1:13 pm, fuzuo xie <xiefu... at gmail.com> wrote:
> This is my code , when i run it ,error happed . can you tell me what's the
> reason and modify it ?thank you very much !! the error is "evaluation of
> function gave a result of wrong length"
> e2<-function(a) integrate(function(x) x,lower=0,upper=a)$value
> integrate(e2,lower=0, upper=0.5)$value
>         [[alternative HTML version deleted]]
> ______________________________________________
> R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list