In this practical we will write a simple function that simulates rolling one or more dice.
sample()
The function sample
allows us to draw values from a given set of values, with or without replacement.
It has arguments
x
: a vector of values to draw fromsize
: the number of values to drawreplace
: can we choose the same element of x
multiple times?prob
: a vector of probability weights (by default all elements of x
have equal probability to be drawn)Write the syntax to simulate a single role of a die using the function sample()
(no function yet).
x
and size
.
sample(1:6, size = 1)
## [1] 1
Write your own function that simulates this one role of a die.
<function name> <- function ( <arguments> ) {
<function body>
}
We use the exact syntax from the previous solution as our function body. Since our function does not need any input (it will always do the same thing) the function does not need any arguments.
<- function() {
die sample(1:6, size = 1)
}
die()
## [1] 2
die()
## [1] 2
die()
## [1] 6
Take another look at the description of the function sample()
. How would you need to change the syntax from Task 1 from above to simulate rolling two dice?
size
and you need to specify the argument replace
.
sample(1:6, size = 2, replace = TRUE)
## [1] 3 2
sample
().
<- function(n) {
dice sample(1:6, size = n, replace = TRUE)
}
dice(2)
## [1] 4 2
dice(1)
## [1] 6
dice(10)
## [1] 6 4 6 4 2 4 5 4 4 3
dice()
without specifying the argument n
?dice()
## [1] 6 2 2 6 3 5
By default, the function dice()
will role 6 dice.
This is due to the behaviour of the function sample()
. In the help file for sample()
(run ?sample
) we can read in the section Details:
For
sample
the default forsize
is the number of items inferred from the first argument, so thatsample(x)
generates a random permutation of the elements ofx
(or1:x
).
What can we learn from this?
Re-write the function dice()
so that by default only one die is used.
<- function(n = 1) {
dice sample(1:6, size = n, replace = TRUE)
}
dice()
## [1] 4
dice()
## [1] 5
© Nicole Erler