[R] problem with break command

Petr Savicky savicky at cs.cas.cz
Thu Apr 26 22:27:45 CEST 2012


On Thu, Apr 26, 2012 at 02:49:08PM -0500, cassie jones wrote:
> Thanks Berend, you are right. The break command would not work here. But
> the while loop is taking time to generate the desired.
> 
> On Thu, Apr 26, 2012 at 2:39 PM, Berend Hasselman <bhh at xs4all.nl> wrote:
[...] 
> > You need a while loop for this.
> >
> > i <- 2
> > while( i <= 5 )
> > # for(i in 2:5)
> > {
> >   a[i] <- a[i-1]+runif(1,0,3)
> >   if(a[i]>5) i <- 2 else i <- i+1
> > }
> >
> > And hope that the while loop will eventually terminate.

Hi.

a[i] is the sum of (i-1) independent realizations of runif(1,0,3),
so a[5] has the mean 6 and standard deviation sqrt(3). The probability
that it is less than 5 may be estimated as

  x <- matrix(runif(4*100000, 0, 3), nrow=100000, ncol=4)
  mean(rowSums(x) < 5)
  [1] 0.28719

If you want to generate a larger number of instances, which terminate
below 5, try

  x <- matrix(runif(4*20, 0, 3), nrow=20, ncol=4)
  a <- matrix(0, nrow=4, ncol=5)
  a[col(a) > row(a)] <- 1
  y <- x[rowSums(x) < 5, ] %*% a

Petr Savicky.



More information about the R-help mailing list