เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ค่าเริ่มต้นเป็น NULL

ฟังก์ชัน cut() ที่ใช้โดย cut_by_quantile() สามารถสร้าง label ที่เหมาะสมให้แต่ละหมวดหมู่โดยอัตโนมัติ โค้ดที่ใช้สร้าง label เหล่านี้ค่อนข้างซับซ้อน ดังนั้นแทนที่จะกำหนดค่าไว้ใน signature ของฟังก์ชันโดยตรง อาร์กิวเมนต์ labels จะมีค่าเริ่มต้นเป็น NULL และรายละเอียดการคำนวณจะแสดงในหน้าช่วยเหลือของ cut() (docs)

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Introduction to Writing Functions in R

ดูคอร์ส

คำแนะนำการฝึกหัด

  • อัปเดตนิยามของ cut_by_quantile() ให้อาร์กิวเมนต์ labels มีค่าเริ่มต้นเป็น NULL
  • นำอาร์กิวเมนต์ labels ออกจากการเรียกใช้ cut_by_quantile()

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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]"
)
แก้ไขและรันโค้ด