possibly()

Lập trình hàm nâng cao với purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

Giới thiệu về possibly()

possibly() tạo ra một hàm trả về:

  • kết quả

  • giá trị của otherwise

library(purrr)
possible_sum <- possibly(sum, otherwise = "nop")
possible_sum(1)

possible_sum("a")
0

"nop"
Lập trình hàm nâng cao với purrr

Cách dùng possibly()

possibly() có thể trả về:

  • Kiểu logical
ps <- possibly(sum, FALSE)
ps("a")
FALSE
  • Một NA
ps <- possibly(sum, NA)
ps("a")
NA

 

  • Một chuỗi ký tự
ps <- possibly(sum, "nope")
ps("a")
"nope"
  • Một số
ps <- possibly(sum, 0)
ps("a")
0
Lập trình hàm nâng cao với purrr

Cùng luyện tập nào!

Lập trình hàm nâng cao với purrr

Preparing Video For Download...