The game is to roll a pair of dice until a sum of 5 or 7 is reached. Then, what is the probability that a sum of 5 comes before a sum of 7?
We use a few handly R commands to answer the problem.
1. expand.grid: gives all combinations of vectors – in our case, two dice.
rolls <- expand.grid(seq(1,6), seq(1,6))
2. do.call: executes a function on a list of arguments, e.g. to perform + (sum) to the earlier list.
sum_rolls <- do.call(`+`, rolls)
2 3 4 5 6 7 3 4 5 6 7 8 4 5 6 7 8 9 5 6 7 8 9 10 6 7 8 9 10 11 7 8 9 10 11 12
3. table function to tabulate each categorical variable (2 to 12) with its frequencies.
tab_rolls <- table(sum_rolls)
sum_rolls
2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 5 4 3 2 1
The table shows that the sum 5 occurs 4 times, and 7 can occur 6 times (out of the 36 possibilities). So, the probability of getting a five before seven (as the sum) is 4/(4+6) = 40%.
Combining steps into 2 lines.
dice_roll <- as.data.frame.table(prop.table(table(do.call(`+`, expand.grid(seq(1,6), seq(1,6))))))
dice_roll$Freq[which(dice_roll$Var1 == 5)] / (dice_roll$Freq[which(dice_roll$Var1 == 5)] + dice_roll$Freq[which(dice_roll$Var1 == 7)])