自定义错误逻辑
有时候,assertive 包中的 assert_*() 函数给出的错误信息不够明确。比如,检查数值是否在数值区间内的断言会提示用户某个值超出范围,但并不会说明这为何是个问题。此时,您可以结合使用 is_*() 函数与消息、警告或错误,来定义自定义反馈。
调和平均数只在 x 的所有取值都为正时才有意义。(试着计算 1 和 -1 的调和平均,您就会明白原因。)请让您的用户清楚这一点!
本练习是课程的一部分
R 函数编写入门
练习说明
- 如果
x中有任意非正值(忽略NA),则抛出错误。 - 查看当您向
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)