Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simulating rolling two dice

Tags:

r

I am trying to simulate rolling two dice. I used:

d2 <- sample(1:6, 10^6, replace = T) + sample(1:6, 10^6, replace = T)

and get the expected result. I also tried

s2d <- c()
for (i in 1:6) { 
  for (j in 1:6){ 
    s2d <- c(s2d, (i+j)) 
  } 
}
d2 <- sample(s2d, 10^6, replace=T)

and that works too, but these feel a bit "brute force." Is there an easier, more elegant way to do it?

In more general terms, is there a function that takes 2 (or more) independent events and does operations on them (addition, multiplication)?

like image 946
K Owen - Reinstate Monica Avatar asked Feb 11 '13 20:02

K Owen - Reinstate Monica


3 Answers

If your issue is that you can't roll any arbitrary number of dice, something like:

rowSums(replicate(2, sample(6, 10^6, replace=T)))

Would be more flexible.

like image 93
David Robinson Avatar answered Sep 21 '22 17:09

David Robinson


I agree with David that nothing seems particularly wrong with your first option. Another way to go might be this, if you're really just after the sum of the two dice:

sample(2:12,size = 100,replace = TRUE, prob = table(outer(1:6,1:6,"+")) / 36)
like image 45
joran Avatar answered Sep 19 '22 17:09

joran


There is a dice function in the TeachingDemos package that simulates the rolling of dice (and there is even an option to plot the results, but 1000 rolls would not make a meaningful plot). This may seem a little less brute force, but internally it does similar to what has already been posted. You can use apply or related functions to do things like sum across the columns of the return.

like image 29
Greg Snow Avatar answered Sep 20 '22 17:09

Greg Snow