CommencerCommencer gratuitement

Multiple inputs to functions

If a function should have more than one argument, list them in the function signature, separated by commas.

To solve this exercise, you need to know how to specify sampling weights to sample(). Set the prob argument to a numeric vector with the same length as x. Each value of prob is the probability of sampling the corresponding element of x, so their values add up to one. In the following example, each sample has a 20% chance of "bat", a 30% chance of "cat" and a 50% chance of "rat".

sample(c("bat", "cat", "rat"), 10, replace = TRUE, prob = c(0.2, 0.3, 0.5))

Cet exercice fait partie du cours

Introduction to Writing Functions in R

Afficher le cours

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

coin_sides <- c("head", "tail")
n_flips <- 10
p_head <- 0.8

# Define a vector of weights
weights <- ___

# Update so that heads are sampled with prob p_head
sample(coin_sides, n_flips, replace = TRUE, ___)
Modifier et exécuter le code