开始使用免费开始使用

NULL 默认值

cut_by_quantile() 所用的 cut() 函数可以为每个类别自动生成合理的标签。用于生成这些标签的代码相当复杂,因此它并不会直接出现在函数签名中,而是将其 labels 参数默认设为 NULL,并在 cut() 的帮助页面(文档)中说明计算细节。

本练习是课程的一部分

R 函数编写入门

查看课程

练习说明

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

交互式实操练习

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

# Set the default for labels to NULL
cut_by_quantile <- function(x, n = 5, na.rm = FALSE, 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 labels argument from the call
cut_by_quantile(
  n_visits,
  labels = c("very low", "low", "medium", "high", "very high"),
  interval_type = "(lo, hi]"
)
编辑并运行代码