mappers 入門

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

Colin Fay

Data Scientist & R Hacker at ThinkR

purrr 中的 .f

函式:

  • 對 .x 的每個元素
  • 執行 .f(.x, ...)

數字 $n$:

  • 對 .x 的每個元素
  • 取 .x[$n$]

字元向量 $z$

  • 對 .x 的每個元素
  • 取 .x[$z$]
使用 purrr 的 R 語言中級函式程式設計

.f 作為函式

當 .f 是函式時,可以是:

  • 一般函式
my_fun <- function(x) {
  round(mean(x))
}
map_dbl(visit_2014, my_fun)
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053

 

  • lambda(匿名)函式
map_dbl(visit_2014, function(x) {
  round(mean(x))
})
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053
使用 purrr 的 R 語言中級函式程式設計

Mappers:第 1 部分

mapper:使用單邊公式的匿名函式

# 一個參數 
map_dbl(visits2017, ~ round(mean(.x)))

# 等同於 
map_dbl(visits2017, ~ round(mean(.)))

# 等同於 
map_dbl(visits2017, ~ round(mean(..1)))
使用 purrr 的 R 語言中級函式程式設計

Mappers:第 2 部分

mapper:使用單邊公式的匿名函式

# 兩個參數
map2(visits2016, visits2017, ~ .x + .y)

# 等同於 
map2(visits2016, visits2017, ~ ..1 + ..2)
# 多於兩個參數
pmap(list, ~ ..1 + ..2 + ..3)
使用 purrr 的 R 語言中級函式程式設計

as_mapper()

as_mapper():從 lambda 函式建立 mapper 物件

# 一般函式 
round_mean <- function(x){
    round(mean(x))
}
# 轉為 mapper
round_mean <- as_mapper(~ round(mean(.x))))
使用 purrr 的 R 語言中級函式程式設計

為什麼用 mappers?

Mappers 的優點:

  • 精簡

  • 易讀

  • 可重用

建立 mappers

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

一起來練習吧!

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

Preparing Video For Download...