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!
This exercise is part of the course
Introduction to Writing Functions in R
Exercise instructions
- 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()
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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)