ทำไมโค้ดของคุณอ่านไม่รู้เรื่อง?

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

คำกริยาใน dplyr

select() เลือก คอลัมน์

filter() กรอง แถว

Introduction to Writing Functions in R

ชื่อฟังก์ชันควรมีคำกริยา

  • get
  • calculate (หรือแค่ calc)
  • run
  • process
  • import
  • clean
  • tidy
  • draw
Introduction to Writing Functions in R

`lm()` ตั้งชื่อได้ไม่ดี

  • ตัวย่อไม่ได้อธิบายความหมายในตัวเอง
  • ไม่มีคำกริยา
  • มีโมเดลเชิงเส้นหลายแบบ

ชื่อที่ดีกว่าคือ run_linear_regression()

Introduction to Writing Functions in R

ความอ่านง่าย vs. ความพิมพ์ง่าย

  • ความอ่านง่าย >> ความพิมพ์ง่าย
Introduction to Writing Functions in R

ความอ่านง่าย vs. ความพิมพ์ง่าย

  • ความอ่านง่าย >> ความพิมพ์ง่าย
  • โปรแกรมแก้ไขโค้ดมีระบบ autocomplete

datacamp-autocomplete.png

Introduction to Writing Functions in R

ความอ่านง่าย vs. ความพิมพ์ง่าย

  • ความอ่านง่าย >> ความพิมพ์ง่าย
  • โปรแกรมแก้ไขโค้ดมีระบบ autocomplete
  • กำหนด alias ให้ฟังก์ชันที่ใช้บ่อยได้
h <- head
data(cats, package = "MASS")
h(cats)
  Sex Bwt Hwt
1   F 2.0 7.0
2   F 2.0 7.4
3   F 2.0 9.5
4   F 2.1 7.2
5   F 2.1 7.3
6   F 2.1 7.6
Introduction to Writing Functions in R

อาร์กิวเมนต์ของ `lm()`

args(lm)
function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...)
Introduction to Writing Functions in R

ประเภทของอาร์กิวเมนต์

  • อาร์กิวเมนต์ข้อมูล: สิ่งที่ใช้คำนวณ
  • อาร์กิวเมนต์รายละเอียด: วิธีที่ใช้คำนวณ
args(cor)
function (x, y = NULL, use = "everything", 
  method = c("pearson", "kendall", "spearman"))
Introduction to Writing Functions in R

อาร์กิวเมนต์ข้อมูลควรอยู่ก่อนอาร์กิวเมนต์รายละเอียด

โค้ดนี้จะไม่ทำงาน

data %>%
  lm(formula)

เพราะอาร์กิวเมนต์ข้อมูลไม่ได้อยู่ตำแหน่งแรก

Introduction to Writing Functions in R

ฟังก์ชัน linear regression ที่ปรับปรุงแล้ว

run_linear_regression <- function(data, formula) {
  lm(formula, data)
}
cats %>% 
  run_linear_regression(Hwt ~ Bet + Sex)
Call:
lm(formula = formula, data = data)

Coefficients:
(Intercept)          Bwt         SexM  
    -0.4150       4.0758      -0.0821
Introduction to Writing Functions in R

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

Introduction to Writing Functions in R

Preparing Video For Download...