# [R] Dice simulation: Getting rep to re-evaluate sample()?

Thomas Lumley tlumley at u.washington.edu
Tue Oct 9 00:55:20 CEST 2007

```
A much easier way to do this, and what Kevin probably was looking for, is
replicate().

replicate(100, sum(sample(1:6,10, replace=TRUE)))

gives 100 sums of 10 fair dice.

-thomas

On Mon, 8 Oct 2007, Alberto Monteiro wrote:

> Kevin Zembower wrote:
>>
>> I'm trying to get R to simulate the sum of the values on 10 fair dice
>> (yes, it's related to a homework problem, but is not the problem
>> itself). I tried to do this:
>>> rep(sum(sample(1:6,100,replace=T)), times=10)
>>  [1] 341 341 341 341 341 341 341 341 341 341
>>
> rep(stuff, times=10) will just take stuff and repeat 10 times.
> stuff is constant (but every time you repeat that line you
> get a different stuff to be repeated), so you get a vector
> of 10 equal numbers.
>
>> I overcome this, so that I get a vector of values that correspond to
>> independent throws of 10 dice each time?
>>
> # get 10*100 random d6s
> x <- sample(1:6, 10*100, replace=T)
>
> # transform into a 10 x 100 matrix
> y <- matrix(x, 10, 100)
>
> # sum the cols
> z <- colSums(y)
>
> Of course, you can combine these three lines into one.
>
> Alberto Monteiro
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help