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

Fixing function arguments

The harmonic mean function is almost complete. However, you still need to provide some checks on the na.rm argument. This time, rather than throwing errors when the input is in an incorrect form, you are going to try to fix it.

na.rm should be a logical vector with one element (that is, TRUE, or FALSE).

The assertive package is loaded for you.

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

Introduction to Writing Functions in R

ดูคอร์ส

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

  • Update calc_harmonic_mean() to fix the na.rm argument by using use_first() to select the first na.rm element, and coerce_to() to change it to logical.

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

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

# Update the function definition to fix the na.rm argument
calc_harmonic_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)
  if(any(is_non_positive(x), na.rm = TRUE)) {
    stop("x contains non-positive values, so the harmonic mean makes no sense.")
  }
  # Use the first value of na.rm, and coerce to logical
  ___ <- ___(___(___), ___ = "___")
  x %>%
    get_reciprocal() %>%
    mean(na.rm = na.rm) %>%
    get_reciprocal()
}

# See what happens when you pass it malformed na.rm
calc_harmonic_mean(std_and_poor500$pe_ratio, na.rm = 1:5)
แก้ไขและรันโค้ด