開始使用免費開始

數值型預設值

cut_by_quantile() 會把數值向量轉換成類別變數,並以分位數作為切割點。這個函式很好用,但目前你必須指定 5 個引數才能運作。思考與輸入都太花時間了。

透過設定預設引數,可以讓它更好用。我們先從 n 開始,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]"
)
編輯並執行程式碼