Rolf Turner r.turner at auckland.ac.nz
Thu Nov 21 22:35:51 CET 2013

```
Think about what you are actually getting from pnorm().

For each scalar "s" you want to get

pnorm(s,mu,sigma)    pnorm(s,mu,sigma)
pnorm(s,mu,sigma)

(and then take products of things).

But when "s" is a vector you get

pnorm(s,mu,sigma)    pnorm(s,mu,sigma)
pnorm(s,mu,sigma)

pnorm(s,mu,sigma)    pnorm(s,mu,sigma)
pnorm(s,mu,sigma) ...

and the product will be nothing like what you want.

Vectors get re-cycled in R.

Note that you get a single scalar quantity from the "prod(1 -
pnorm(...))" component of
test2().  That single scalar multiplies each entry of the vector
dnorm(s,mu,sigma).

Whereas you want dnorm(s[i],mu,sigma) to be multiplied by a
product involving
only pnorm() terms evaluated at s[i].  That is what Vectorize() arranges
for you.

If you are going to use R you should learn its syntax and know about
things like the
re-cycling of vectors.

cheers,

Rolf Turner

On 11/22/13 04:46, dan wang wrote:
> Hi all,
>
> I tried below two methods to calculate the integrate of a same function.
> Two different results are given.
> The first one should be the right answer.
> Can any one help to explain why?
> Another issue is, the first one is not convenient as I have to update the
> mu and sigma outside the function. How can I modify the second one so I
> could issue the parameters in the integrate function.
>
> Dan
>
> test <- function(s){
>         prod(1-pnorm(s,mu[-1],sigma[-1]))*dnorm(s,mu,sigma)
>
> }
> testV <- Vectorize(test)
> mu=c(0,0,0,0)
> sigma=c(1,1,1,1)
> integrate(testV,lower=-Inf,upper=Inf)\$value
>
>
> test2 <- function(s, mu, sigma){
>         prod(1-pnorm(s,mu[-1],sigma[-1]))*dnorm(s,mu,sigma)
>
> }
> integrate(test2,mu=c(0,0,0,0),sigma=c(1,1,1,1),lower=-Inf,upper=Inf)\$value

```