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
.
This exercise is part of the course
Introduction to Writing Functions in R
Exercise instructions
- Update the definition of
cut_by_quantile()
so that then
argument defaults to5
. - Remove the
n
argument from the call tocut_by_quantile()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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]"
)