[R] using "integrate" in a function definition

theo borm theo.borm at wur.nl
Fri Feb 23 22:36:55 CET 2007


Ravi Varadhan wrote:

>Your function "jjj" is not vectorized.
>
>Try this:
>
>jjj <- function(www) sapply(www, function(x)2*integrate(dnorm,0,x)$value)
>plot(jjj, 0, 5)
>
>It should work.
>  
>
Yes it does. Thanks!

Thinking of it, it now starts to make some sort of sense that integrate 
should return a "scalar"; the result is really a list of which I only 
used the "value" component. And now I also understand the "x,q: vector 
of quantiles." phrases in the documentation of dnorm.

Now if I do something silly:
 > jjj<-function(www) {2*integrate(dnorm,0,www)$value+sin(www)-sin(www)}
then
 > jjj(1:5)
[1] 0.6826895 0.6826895 0.6826895 0.6826895 0.6826895

Evidently the "inherritance" of "being vectorized" (which was why my kkk 
function worked) could lead to some unexpected (and probably hard to 
debug) results :-/

Thanks.


with kind regards,

Theo.



More information about the R-help mailing list