purrr 的函數式程式設計工具

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

Colin Fay

Data Scientist & R Hacker at ThinkR

高階函式

高階函式可以:

  • 接收一個或多個函式作為引數
  • 回傳一個函式
nop_na <- function(fun){
  function(...){
    fun(..., na.rm = TRUE)
  }
}

sd_no_na <- nop_na(sd) sd_no_na( c(NA, 1, 2, NA) )
0.7071068
使用 purrr 的 R 語言中級函式程式設計

三種高階函式

  • Functionals

  • 函式工廠

  • 函式運算子

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

purrr 的副詞(adverbs)

處理錯誤與警告:

  • possibly()
  • safely()
library(purrr)
safe_mean <- safely(mean)
class(safe_mean)
"function"
使用 purrr 的 R 語言中級函式程式設計

用 safely() 處理錯誤。

safely() 回傳一個函式,該函式會回傳:

  • $result
  • $error
safe_log <- safely(log)
safe_log("a")
$result
NULL
$error
<simpleError in log(x = x, base = base): non-numeric argument to mathematical function>
使用 purrr 的 R 語言中級函式程式設計
map( list(2, "a"), log )
Error in log(x = x, base = base) : non-numeric argument to mathematical function
map( list(2, "a"), safely(log) )
[[1]]
[[1]]$result
[1] 0.6931472

[[1]]$error
NULL

[[2]]
[[2]]$result
NULL

[[2]]$error
<simpleError in log(x = x, base = base):non-numeric argument to mathematical function>
使用 purrr 的 R 語言中級函式程式設計

從 `safely()` 的結果取出元素

map()"result""error"

safe_log <- safely(log)

map( list("a", 2),  safe_log) %>% 
  map("result")
[[1]]
NULL

[[2]]
[1] 0.6931472

 

safe_log <- safely(log)

map( list("a", 2), safe_log ) %>% 
  map("error")
[[1]]
<simpleError in log(x = x, 
base = base): non-numeric argument 
to mathematical function>

[[2]]
NULL
使用 purrr 的 R 語言中級函式程式設計

一起來練習吧!

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

Preparing Video For Download...