恭喜你!

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

Colin Fay

Data-Scientist & R-Hacker @ ThinkR

Lambda 函式:

map(1:5, ~ .x*10)
[[1]]
[1] 10

[[2]]
[1] 20

[[3]]
[1] 30

[[4]]
[1] 40

[[5]]
[1] 50

可重用的對映器:

ten_times <- as_mapper(~ .x * 10)
map(1:5, ten_times)
[[1]]
[1] 10

[[2]]
[1] 20

[[3]]
[1] 30

[[4]]
[1] 40

[[5]]
[1] 50
使用 purrr 的 R 語言中級函式程式設計

操作函式

函式化工具:

  • map() 與相關函式

  • keep()discard()

  • some()every()

函式運算子:

  • safely()possibly()

  • partial()

  • compose()

  • negate()

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

更乾淨的程式碼

library(purrr)
rounded_mean <- compose(
  partial(round, digits = 1),
  partial(mean, trim = 2, na.rm = TRUE))
map(list(airquality, mtcars), 
  ~ map_dbl(.x, rounded_mean))
[[1]]
Ozone Solar.R    Wind    Temp   Month     Day 
 31.5   205.0     9.7    79.0     7.0    16.0 

[[2]]
 mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb 
19.2   6.0 196.3 123.0   3.7   3.3  17.7   0.0   0.0   4.0   2.0
使用 purrr 的 R 語言中級函式程式設計

接下來去哪裡?

  • 去實際試試 purrr ;)

  • DataCamp 的 tidyverse 課程

  • Advanced R

  • 繼續探索 purrr

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

下次見!

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

Preparing Video For Download...