[R] using "integrate" in a function definition

Alberto Monteiro albmont at centroin.com.br
Fri Feb 23 19:18:01 CET 2007

theo borm wrote: 
>> jjj<-function(www) {2*integrate(dnorm,0,www)$value} 
>> kkk<-function(www) {2*(pnorm(www)-0.5)} 

>> xxx<-seq(0:5) 
>> yyy<-jjj(xxx) 
>> zzz<-kkk(xxx) 
> produces no errors, but: 
>> yyy 
> [1] 0.6826895 
>> zzz 
> [1] 0.6826895 0.9544997 0.9973002 0.9999367 0.9999994 1.0000000 
> Why is this? Is this some R language feature that I've completely missed? 
Yes. Some functions work on vectors (and matrices), so 
when you give a vector, it returns a vector. This is true for 
most common functions (sin, cos), arithmetic operations (with 
the caveat that different dimensions for the arguments may cause 
unexpected outcomes) and some internal functions (dnorm, pnorm). 
So, if you write sin(0:10) or dnorm((-3):3), you get a vector. 

Some other functions don't, and this is the case with integrate. 
For example: 

fff <- function(x) x 
integrate(fff, 0, 1)  # ok 
integrate(fff, 0, 1:5) # will integrate from 0 to 1 and ignore 2:5 

'plot' will probably fall into some code that uses this 
vector-in-vector-out hypothesis, and then fail when the size 
of x differs from the size of y. 

Alberto Monteiro 

PS: fff <- function(x) 1 
integrate(fff, 0, 1)  # error. why?

More information about the R-help mailing list