[R] using integrate on a function defined with if

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Sat Jun 15 08:55:15 CEST 2002


On Sat, 15 Jun 2002, 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.

No, in the first case it is vector of length 1, and in the second a vector
of the length of x.   Did you actually try it?  Please do to convince
yourself.

S functions return the value of their last statement.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list