Learn R Programming

TeachingDemos (version 1.2)

dice: Simulate rolling dice

Description

Simulate and optionally plot rolls of dice.

Usage

dice(rolls = 1, ndice = 2, sides = 6, plot.it = FALSE, load = rep(1, sides))
plot.dice(x, ...)

Arguments

rolls
Scalar, the number of times to roll the dice.
ndice
Scalar, the number of dice to roll each time.
sides
Scalar, the number of sides per die.
plot.it
Logical, Should the results be plotted.
load
Vector of length sides, how the dice should be loaded.
x
Data frame, return value from dice.
...
Additional arguments passed to lattice plotting function.

Value

  • A data frame with rolls rows and ndice columns representing the results from rolling the dice. If only 1 die is rolled, then the return value will be a vector. If plot.it is TRUE, then the return value will be invisible.

Details

Simulates the rolling of dice. By default it will roll 2 dice 1 time and the dice will be fair. Internally the sample function is used and the load option is passed to sample. load is not required to sum to 1, but the elements will be divided by the sum of all the values.

See Also

sample

Examples

Run this code
# 10 rolls of 4 fair dice
dice(10,4, plot.it=TRUE)

# or

plot(dice(10,4))

# or 

tmp <- dice(10,4)
plot(tmp)

# a loaded die
table(tmp <- dice(100,1,plot.it=TRUE, load=6:1 ) )
mean(tmp)

## redo De Mere's question

demere1 <- dice(10000,4)
demere2 <- dice(10000,24,sides=36)

mean(apply( demere1, 1, function(x) 6 %in% x ))

mean(apply( demere2, 1, function(x) 36 %in% x))

plot(demere1[1:10,])

## plot all possible combinations of 2 dice

plot.dice( expand.grid(1:6,1:6), layout=c(6,6) )

Run the code above in your browser using DataLab