ค่าเริ่มต้นแบบกลุ่มตัวเลือก
เมื่อตัดแบ่ง numeric vector ออกเป็นช่วง สิ่งที่ต้องคำนึงถึงคือกรณีที่ค่าหนึ่งตกพอดีที่ขอบเขต จะนำค่านั้นเข้าไปในช่วงล่างหรือช่วงบนดี กล่าวคือ สามารถเลือกให้ช่วงรวมค่าที่ขอบบนแต่ไม่รวมขอบล่าง (ในทางคณิตศาสตร์เรียกว่า "เปิดทางซ้าย ปิดทางขวา" หรือ (lo, hi]) หรือจะเลือกแบบตรงข้าม ("ปิดทางซ้าย เปิดทางขวา" หรือ [lo, hi)) ก็ได้ ฟังก์ชัน cut_by_quantile() ควรรองรับทั้งสองตัวเลือกนี้
รูปแบบสำหรับค่าเริ่มต้นแบบกลุ่มตัวเลือกมีดังนี้:
function(cat_arg = c("choice1", "choice2")) {
cat_arg <- match.arg(cat_arg)
}
คำใบ้เพิ่มเติม: ลองพิมพ์ head(rank) ในคอนโซลเพื่อดูส่วนต้นของนิยามฟังก์ชัน rank() แล้วสังเกตอาร์กิวเมนต์ ties.method
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Introduction to Writing Functions in R
คำแนะนำการฝึกหัด
- อัปเดต signature ของ
cut_by_quantile()เพื่อให้อาร์กิวเมนต์interval_typeรับค่าได้ทั้ง"(lo, hi]"และ"[lo, hi)"สังเกตว่ามีช่องว่างหลังเครื่องหมายจุลภาคแต่ละตัว - อัปเดตส่วน body ของ
cut_by_quantile()เพื่อให้จับคู่กับอาร์กิวเมนต์interval_type - ลบอาร์กิวเมนต์
interval_typeออกจากการเรียกใช้cut_by_quantile()
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Set the categories for interval_type to "(lo, hi]" and "[lo, hi)"
cut_by_quantile <- function(x, n = 5, na.rm = FALSE, labels = NULL,
interval_type) {
# Match the interval_type argument
___ <- ___
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 interval_type argument from the call
cut_by_quantile(n_visits, interval_type = "(lo, hi]")