# [R] using integrate on a function defined with if

Ole Christensen o.christensen at lancaster.ac.uk
Sat Jun 15 11:53:37 CEST 2002

```Hi Faheem

``integrate'' requires that the function (foo in your example)
takes a vector as the first argument and returns a vector of the same
length.

To illustrate this, try making a check for x being a vector in your
first example

foo <- function(x){
if(is.vector(x)) print("x is a vector ! ")
if(x==0) 4
else 0
}

integrate(foo,0,1)

gives

[1] "x is a vector ! "
Error in integrate(foo, 0, 1) : evaluation of function gave a result of
wrong length

As Prof. Ripley wrote in his reply, the problem is that your function is
not returning a vector but a number.

Cheers Ole

Faheem Mitha wrote:
>
> Dear R People,
>
> I getting some curious behaviour with the integrate function. Consider the
> function
>
> foo <- function(x)
>   {
>     if(x==0)
>         4
>         else
>         0
>         }
>
> I get the error
>
> > integrate(foo,0,1)
> Error in integrate(foo, 0, 1) : evaluation of function gave a result of
> wrong length
>
> But now consider
>
> foo <- function(x)
>   {
>     ifelse(x==0,4,0)
>   }
>
> > integrate(foo,0,1)
> 0 with absolute error < 0
>
> I am guessing this may have something to do with types/classes, but I
> don't see exactly what. I would be happy to be enlightened.
>
> Yhe help page says the function must be
>
> "f An R function taking a numeric first argument and returning a numeric
> vector the same length."
>
> But I don't see any difference in what these two return. In both cases it
> is NULL.
>
>                                   Sincerely, Faheem Mitha.
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

--
Ole F. Christensen
Department of Mathematics and Statistics
Fylde College, Lancaster University
Lancaster, LA1 4YF, England
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```