ComeçarComece de graça

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!

Este exercício faz parte do curso

Introduction to Writing Functions in R

Ver curso

Instruções do exercício

  • If any values of x are non-positive (ignoring NAs) then throw an error.
  • Look at what happens when you pass a character argument to calc_harmonic_mean().

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

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)
Editar e executar o código