开始使用免费开始使用

逻辑型默认值

cut_by_quantile() 现在用起来更方便了一点,但您仍然每次都得指定 na.rm 参数。这个参数会移除缺失值——它的行为与 mean()sd() 中的 na.rm 参数相同。

当函数提供用于移除缺失值的参数时,最佳实践是默认移除(以防您没有注意到数据中存在缺失值)。也就是说,na.rm 的默认值应为 FALSE

本练习是课程的一部分

R 函数编写入门

查看课程

练习说明

  • 更新 cut_by_quantile() 的定义,使 na.rm 参数的默认值为 FALSE
  • 从对 cut_by_quantile() 的调用中移除 na.rm 参数。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Set the default for na.rm to FALSE
cut_by_quantile <- function(x, n = 5, na.rm, labels, interval_type) {
  probs <- seq(0, 1, length.out = n + 1)
  qtiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
  right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
  cut(x, qtiles, labels = labels, right = right, include.lowest = TRUE)
}

# Remove the na.rm argument from the call
cut_by_quantile(
  n_visits, 
  na.rm = FALSE, 
  labels = c("very low", "low", "medium", "high", "very high"),
  interval_type = "(lo, hi]"
)
编辑并运行代码