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

Julian M Burgos jmburgos at u.washington.edu
Mon Oct 8 23:04:06 CEST 2007


Well, if the dice are fair, then all rolls are independent.  If you want to roll each dice 100 times, you can do something like

rolls=matrix(sample(1:6,1000,replace=T),ncol=10)

apply(rolls,2,sum)

I'm sure that there must be a more elegant way to do it, though.

Julian


On Mon, 8 Oct 2007, Zembower, Kevin 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
>
> and noticed that sum(sample()) seems to be only evaluated once. How can
> I overcome this, so that I get a vector of values that correspond to
> independent throws of 10 dice each time?
>
> Thanks for your advice and suggestions.
>
> -Kevin
>
> Kevin Zembower
> Internet Services Group manager
> Center for Communication Programs
> Bloomberg School of Public Health
> Johns Hopkins University
> 111 Market Place, Suite 310
> Baltimore, Maryland  21202
> 410-659-6139
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list