Numeric defaults
cut_by_quantile() converts a numeric vector into a categorical variable where quantiles define the cut points. This is a useful function, but at the moment you have to specify five arguments to make it work. This is too much thinking and typing.
By specifying default arguments, you can make it easier to use. Let's start with n, which specifies how many categories to cut x into.
A numeric vector of the number of visits to Snake River is provided as n_visits.
Den här övningen är en del av kursen
Introduction to Writing Functions in R
Övningsinstruktioner
- Update the definition of
cut_by_quantile()so that thenargument defaults to5. - Remove the
nargument from the call tocut_by_quantile().
Interaktiv övning med praktiskt arbete
Testa den här övningen genom att slutföra den här exempelkoden.
# Set the default for n to 5
cut_by_quantile <- function(x, n, na.rm, labels, interval_type) {
probs <- seq(0, 1, length.out = n + 1)
qtiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
cut(x, qtiles, labels = labels, right = right, include.lowest = TRUE)
}
# Remove the n argument from the call
cut_by_quantile(
n_visits,
n = 5,
na.rm = FALSE,
labels = c("very low", "low", "medium", "high", "very high"),
interval_type = "(lo, hi]"
)