Logical defaults
cut_by_quantile()
is now slightly easier to use, but you still always have to specify the na.rm
argument. This removes missing values—it behaves the same as the na.rm
argument to mean()
or sd()
.
Where functions have an argument for removing missing values, the best practice is to not remove them by default (in case you hadn't spotted that you had missing values). That means that the default for na.rm
should be FALSE
.
This exercise is part of the course
Introduction to Writing Functions in R
Exercise instructions
- Update the definition of
cut_by_quantile()
so that thena.rm
argument defaults toFALSE
. - Remove the
na.rm
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 na.rm to FALSE
cut_by_quantile <- function(x, n = 5, 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 na.rm argument from the call
cut_by_quantile(
n_visits,
na.rm = FALSE,
labels = c("very low", "low", "medium", "high", "very high"),
interval_type = "(lo, hi]"
)