शुरू करेंमुफ़्त में शुरू करें

Throwing errors with bad arguments

If a user provides a bad input to a function, the best course of action is to throw an error letting them know. The two rules are

  1. Throw the error message as soon as you realize there is a problem (typically at the start of the function).
  2. Make the error message easily understandable.

You can use the assert_*() functions from assertive to check inputs and throw errors when they fail.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Introduction to Writing Functions in R

पाठ्यक्रम देखें

अभ्यास निर्देश

  • Add a line to the body of calc_harmonic_mean() to assert that x is numeric.
  • Look at what happens when you pass a character argument to calc_harmonic_mean().

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

calc_harmonic_mean <- function(x, na.rm = FALSE) {
  # Assert that x is numeric
  ___
  x %>%
    get_reciprocal() %>%
    mean(na.rm = na.rm) %>%
    get_reciprocal()
}

# See what happens when you pass it strings
calc_harmonic_mean(std_and_poor500$sector)
कोड संपादित करें और चलाएँ