Hi:

This problem is a useful lesson in the power of vectorizing calculations in
R.

A remanufacturing of your function:

dubloop <- function(nsim) {
    count <- 0
       for(j in 1:nsim){           #begin loop
           die1 <- sample(1:6,1)
           die2 <- sample(1:6,1)
           if(die1 == die2) count <- count + 1 else count <- count
                      }           #end loop
    emprob <- count/nsim
    list(count = count, emprob = emprob)
  } #end program

Interestingly, you used ifelse(), which is a *vectorized* if-else function,
inside a loop,
so I replaced it with the more appropriate if-else construct for scalar
comparisons. My
version of Jeffrey's vectorization of your function (which is the same save
for variable naming) is

dubs <- function(n) {
     x1 <- sample(1:6, n, replace = TRUE)
     x2 <- sample(1:6, n, replace = TRUE)
     round(sum(x1 == x2)/n, 3)
   }

Let's compare their timings:

system.time(replicate(1000, dubloop(1000)))
   user  system elapsed
  16.36    0.00   16.41
system.time(replicate(1000, dubs(1000)))
   user  system elapsed
   0.08    0.00    0.08

The vectorized version is over 200 times faster than the loop. In R,
vectorization pays
dividends (sometimes big ones) when the operation is amenable to it.  This
is an
important lesson to learn when migrating to R from a traditional programming
language.

HTH,
Dennis




On Mon, Oct 4, 2010 at 9:13 PM, Lemarian WallaceIII <tott...@yahoo.com>wrote:

> Im trying to simulate the rolling of a pair of dice
>
> this is my function:
> #function to simulate tosses of a pair of dice
> #from the simulation, the program returns the empirical probability of
> #observing a double
> count <- 0
> for(j in 1:sim){#begin loop
> die1 <- sample(1:6,1)
> print(die1)
> die2 <- sample(1:6,1)
> print(die2)
> count <- ifelse(die1 == die2, count + 1, count)
> }#end loop
> emprob <- count/sim
> return(count,emprob)
> } #end program
>
>
> these are the errors that keep coming up:
> Error in 1:sim : 'sim' is missing
>
>
> How do I correct this?
>
>
>
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to