Kom igångKom igång gratis

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))

Den här övningen är en del av kursen

Introduction to Writing Functions in R

Visa kurs

Interaktiv övning med praktiskt arbete

Testa den här övningen genom att slutföra den här exempelkoden.

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, ___)
Redigera och kör kod