How to evaluate the probability of a range in R?

44 views Asked by At

Supposed I toss 10 dice many times (let's say, 10000 times), and I want to know the probability of the sum on 10 dice falling into a range (10 to 20, 20 to 30, ..., 50 to 60). How can I divide the value into range and calculate the probability of each range? Below is what I have til now:

K=10 
all_comb = rep(list(1:6),K) # set up the dice
dice <- expand.grid(all_comb) #list all possible combinations
dice.sums <- rowSums(dice) #calculate sum of each combination
all_prob = c() #calculate the probability of each possible sum (from 10 to 60)
for (i in 1:(60-10+1) ){
  a = mean( dice.sums == c(10:60)[i] ) 
  all_prob = c(all_prob,a)
}
print(all_prob)

I hope someone can tell me how to do this. Thank you very much!

2

There are 2 answers

0
Allan Cameron On

If you create a table of dice.sums, then you will get the frequency of each possible sum. Dividing this table by its total will give you the probability of each sum. The rest is just data wrangling to get it into the correct format, for which dplyr will be useful:

library(dplyr)

table(dice.sums) %>%
  as.data.frame() %>%
  mutate(dice.sums = as.numeric(as.character(dice.sums)),
         prob = Freq/sum(Freq),
         floor = 10 * floor(dice.sums/10)) %>%
  summarise(range = paste(min(dice.sums), max(dice.sums), sep = ' - '),
            prob = round(sum(prob), 8), .by = floor) %>%
  select(range, prob)
#>     range       prob
#> 1 10 - 19 0.00148046
#> 2 20 - 29 0.15502340
#> 3 30 - 39 0.63852791
#> 4 40 - 49 0.20207825
#> 5 50 - 59 0.00288996
#> 6 60 - 60 0.00000002
0
jay.sf On

Perhaps you could simply do,

> n_dice <- 10
> n_toss <- 1e6
> set.seed(42)
> tss <- replicate(n_dice, sample.int(6, n_toss, replace=TRUE))
> table(cut(rowSums(tss), seq(0, 6*n_dice, 10)))/n_toss

  (0,10]  (10,20]  (20,30]  (30,40]  (40,50]  (50,60] 
0.000000 0.002883 0.202386 0.638278 0.154963 0.001490