Dice throws in R

Below some code to look at the observed and expected probability to find the different values of the sum of two six faced fair dice.

library(ggplot2)
# function to generate dice throws
des <- function(time) {
    # this is the theoretical distributions of the resulting values, there is
    # one chance out of 36 to get 2, 2 chance out of 36 to get 3...
    true <- c(1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1)/36
    # these are the sums of our two throws, and since we are throwing the same
    # number over and over again we have to set replace =TRUE
    res <- sample(1:6, size = time, replace = TRUE) + sample(1:6, size = time, 
        replace = TRUE)
    # a resulting data frame for later use, when time is low there is some
    # chance that we will not get all numbers between 2 and 12, therefore the
    # specification of the Value and Exp column is not that straightforward
    out <- data.frame(Value = c(unique(res)[order(unique(res))], 2:12), Res = c(table(res)/time, 
        true), Exp = c(rep("Observed", length(unique(res))), rep("Theoretical", 
        11)))
    # plotting
    print(ggplot(out, aes(x = Value, y = Res, fill = Exp)) + geom_histogram(stat = "identity", 
        position = "dodge") + scale_x_discrete(breaks = c(2:12)))
}

We can now simulate with few throws:

des(10)

plot of chunk unnamed-chunk-2

And now with lots of them:

des(1e+05)

plot of chunk unnamed-chunk-3