Writing a simple function
Let's write a simple function to do a typical task in this course. Here, our function will simulate the rolling of dice and report the sum of the values that appear. Our function will allow the user to choose how many dice they would like to roll.
Although R cannot physically roll dice for us, we can simulate an equivalent process by taking random draws from the set of numbers {1, 2, 3, 4, 5, 6} with equal probability. Using the sample
function is one way to accomplish this.
Este ejercicio forma parte del curso
Probability Puzzles in R
Instrucciones del ejercicio
- Using the
sample
function, specify thesize
andreplace
parameters. - Calculate the sum of the rolls.
return
the object containing the answer.- Run the function for a roll of five dice.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
# Set seed to 1
set.seed(1)
# Write a function to roll k dice
roll_dice <- function(k){
all_rolls <- sample(c(1,2,3,4,5,6),
___,
replace = ___)
final_answer <- ____
return(___)
}
# Run the function to roll five dice
roll_dice(___)