開始使用免費開始

修正函式引數

調和平均數函式已經快完成了。不過,關於 na.rm 引數,你還需要加入一些檢查。這次不要在輸入格式不正確時直接拋出錯誤,而是嘗試自動修正它。

na.rm 應該是只含一個元素的邏輯向量(也就是 TRUEFALSE)。

已為你載入 assertive 套件。

本練習屬於課程

R 函式撰寫入門

檢視課程

練習說明

  • 更新 calc_harmonic_mean(),利用 use_first() 先選取 na.rm 的第一個元素,再用 coerce_to() 將其轉換為邏輯型別,以修正 na.rm 引數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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)
編輯並執行程式碼