BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Probability Puzzles in R

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • 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.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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(___)
Kodu Düzenle ve Çalıştır