為什麼要更乾淨的程式碼?

使用 purrr 的 R 語言中級函式程式設計

Colin Fay

Data Scientist & R Hacker

威利在哪裡?

library(broom)
library(dplyr)
lm(Sepal.Length ~ Species, data=iris) %>% tidy() %>% filter(p.value < 0.05)
lm(Pepal.Length ~ Species, data=iris) %>% tidy() %>% filter(p.value < 0.05)
lm(Sepal.Width ~ Species, data=iris) %>% tidy() %>% filter(p.value < 0.05)
lm(Sepal.Length ~ Species, data=iris) %>% tidy() %>% ilter(p.value < 0.05)
使用 purrr 的 R 語言中級函式程式設計

找出威利

library(purrr)
tidy_iris_lm <- compose(
  as_mapper(~ filter(.x, p.value < 0.05)), 
  tidy, 
  partial(lm, data=iris, na.action = na.fail)
)

list( Petal.Length ~ Petal.Width, Petal.Width ~ Sepal.Width, Sepal.Width ~ Sepal.Length ) %>% map(tidy_iris_lm)
使用 purrr 的 R 語言中級函式程式設計

什麼是乾淨程式碼?

乾淨的程式碼是:

  • 輕量
  • 可讀
  • 易解讀
  • 好維護
使用 purrr 的 R 語言中級函式程式設計

compose()

組合函式:

library(purrr)

rounded_mean <- compose(round, mean)
rounded_mean(1:2811)
1406
使用 purrr 的 R 語言中級函式程式設計

用組合寫更乾淨的程式碼

# FROM
round(mean(1:10))
round(mean(1:100))
round(mean(1:1000))
round(mean(1:10000))
#TO
round(median(1:10))
round(median(1:100))
round(median(1:1000))
round(median(1:10000))

-> 4 個變更

# FROM
my_stats <- compose(round, mean)
my_stats(1:10)
my_stats(1:100)
my_stats(1:1000)
my_stats(1:10000)
#TO
my_stats <- compose(round, median)
my_stats(1:10)
my_stats(1:100)
my_stats(1:1000)
my_stats(1:10000)

-> 1 個變更

使用 purrr 的 R 語言中級函式程式設計

一起來練習吧!

使用 purrr 的 R 語言中級函式程式設計

Preparing Video For Download...