Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Probability Puzzles in R

Cursus bekijken

Oefeninstructies

  • Using the sample function, specify the size and replace parameters.
  • Calculate the sum of the rolls.
  • return the object containing the answer.
  • Run the function for a roll of five dice.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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(___)
Code bewerken en uitvoeren