Custom error logic
Sometimes the assert_*()
functions in assertive
don't give the most informative error message. For example, the assertions that check if a number is in a numeric range will tell the user that a value is out of range, but the won't say why that's a problem. In that case, you can use the is_*()
functions in conjunction with messages, warnings, or errors to define custom feedback.
The harmonic mean only makes sense when x
has all positive values. (Try calculating the harmonic mean of one and minus one to see why.) Make sure your users know this!
Diese Übung ist Teil des Kurses
Introduction to Writing Functions in R
Anleitung zur Übung
- If any values of
x
are non-positive (ignoringNA
s) then throw an error. - Look at what happens when you pass a character argument to
calc_harmonic_mean()
.
Interaktive Übung
Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.
calc_harmonic_mean <- function(x, na.rm = FALSE) {
assert_is_numeric(x)
# Check if any values of x are non-positive
if(___(___(___), na.rm = TRUE)) {
# Throw an error
___("x contains non-positive values, so the harmonic mean makes no sense.")
}
x %>%
get_reciprocal() %>%
mean(na.rm = na.rm) %>%
get_reciprocal()
}
# See what happens when you pass it negative numbers
calc_harmonic_mean(std_and_poor500$pe_ratio - 20)