开始使用免费开始使用

数值型默认值

cut_by_quantile() 会把数值向量转换为由分位数定义切分点的分类变量。这个函数很有用,但目前您必须指定 5 个参数才能运行。思考和输入都太多了。

通过为参数设置默认值,您可以让函数更易用。我们先从 n 开始,它用于指定将 x 切分为多少个类别。

一组表示 Snake River 访问次数的数值向量已作为 n_visits 提供。

本练习是课程的一部分

R 函数编写入门

查看课程

练习说明

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

交互式实操练习

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

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