อาร์กิวเมนต์เริ่มต้น

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

ปัญหาของ toss_coin()

toss_coin <- function(n_flips, p_head) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}

กำหนดค่าเริ่มต้นใน signature

toss_coin <- function(n_flips, p_head = 0.5) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}
Introduction to Writing Functions in R

เทมเพลตพร้อมค่าเริ่มต้น

my_fun <- function(data_arg1, data_arg2, detail_arg1 = default1) {
  # Do something
}
Introduction to Writing Functions in R

ค่าเริ่มต้นประเภทอื่น

args(median)
function (x, na.rm = FALSE, ...)
library(jsonlite)
args(fromJSON)
function (txt, simplifyVector = TRUE, simplifyDataFrame = simplifyVector, 
    simplifyMatrix = simplifyVector, flatten = FALSE, ...)
Introduction to Writing Functions in R

ค่าเริ่มต้นแบบ NULL

ตามธรรมเนียม หมายความว่า

ฟังก์ชันนี้จะจัดการอาร์กิวเมนต์นี้เป็นพิเศษ โปรดอ่านเอกสารประกอบ

args(set.seed)
function (seed, kind = NULL, normal.kind = NULL)
Introduction to Writing Functions in R

ค่าเริ่มต้นแบบหมวดหมู่

  1. ส่ง character vector ใน signature
  2. เรียก match.arg() ใน body
args(prop.test)
function (x, n, p = NULL, alternative = c("two.sided", "less", "greater"), 
  conf.level = 0.95, correct = TRUE)

ภายใน body

alternative <- match.arg(alternative)
Introduction to Writing Functions in R

การแบ่งเวกเตอร์ตาม quantile

cut_by_quantile <- function(x, n, na.rm, labels, interval_type) {
  probs <- seq(0, 1, length.out = n + 1)
  quantiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
  right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
  cut(x, quantiles, labels = labels, right = right, include.lowest = TRUE)
}
  • x: เวกเตอร์ตัวเลขที่ต้องการแบ่ง
  • n: จำนวนหมวดหมู่ที่จะแบ่ง x
  • na.rm: ลบค่าที่หายไปออกหรือไม่?
  • labels: ป้ายกำกับแบบ character สำหรับแต่ละหมวดหมู่
  • interval_type: ช่วงควรเปิดทางซ้ายหรือขวา?
Introduction to Writing Functions in R

น้ำหนักหัวใจแมว

กราฟ strip plot แสดงน้ำหนักหัวใจแมว ค่าอยู่ในช่วง 3 ถึง 20 กรัม

quantile(cats$Hwt)
    0%    25%    50%    75%   100% 
 6.300  8.950 10.100 12.125 20.500
1 data(cats, package = "MASS")
Introduction to Writing Functions in R

การแบ่งตาม quantile

กราฟ strip plot จากสไลด์ก่อนถูกเพิ่มสี โดยจุดทางซ้ายเป็นสีแดง ถัดมาเป็นสีเขียว สีเขียวอมฟ้า และสีม่วงทางขวา

cut(x, quantile(x))
Introduction to Writing Functions in R

มาฝึกกันเถอะ!

Introduction to Writing Functions in R

Preparing Video For Download...