เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

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!

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Introduction to Writing Functions in R

ดูคอร์ส

คำแนะนำการฝึกหัด

  • 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().

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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)
แก้ไขและรันโค้ด