関数引数の修正
調和平均を求める関数は、ほぼ完成しています。ただし、na.rm 引数にいくつかのチェックを追加する必要があります。今回は、入力の形式が正しくないときにエラーを出すのではなく、可能であれば修正する方針にします。
na.rm は、要素数が 1 の論理ベクトル(つまり TRUE または FALSE)である必要があります。
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)