[R] Dice simulation: Getting rep to re-evaluate sample()?
albmont at centroin.com.br
Mon Oct 8 20:42:30 CEST 2007
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)
>  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.
More information about the R-help