Predicates

Functional Programming ระดับกลางด้วย purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

Predicate คืออะไร?

Predicates: คืนค่า TRUE หรือ FALSE

  • ทดสอบเงื่อนไข
  • มีอยู่ใน base R: is.numeric(), %in%, is.character() เป็นต้น

 

is.numeric(10)
TRUE
Functional Programming ระดับกลางด้วย purrr

Predicate functional คืออะไร?

Predicate functionals:

  • รับ element และ predicate
  • ใช้ predicate กับ element นั้น

 

keep(airquality, is.numeric)
Functional Programming ระดับกลางด้วย purrr

every(): ทุก element ตรงตามเงื่อนไขหรือไม่?

# Are all elements of visits2016 numeric?
every(visits2016, is.numeric)

# Is the mean of every months above 1000? every(visits2016, ~ mean(.x) > 1000)
TRUE

FALSE

some(): มีบาง element ตรงตามเงื่อนไขหรือไม่?

# Is the mean of some months above 1000? 
some(visits2016, ~ mean(.x) > 1000)
TRUE
Functional Programming ระดับกลางด้วย purrr

detect_index()

# Which is the first element with a mean above 1000?
detect_index(visits2016, ~ mean(.x) > 1000)
1
# Which is the last element with a mean above 1000?
detect_index(visits2016, ~ mean(.x) > 1000, .right = TRUE)
11
Functional Programming ระดับกลางด้วย purrr

has_element() และ detect()

# What is the value of the first element with a mean above 1000?
detect(visits2016, ~ mean(.x) > 1000, .right = TRUE)
[1] 1289  782 1432 1171 1094 1015  582  946 1191 1393 1307 1125 1267 1345 1066  810  583 
[18] 733  795  766  873  656 1018  645  949  938 1118 1106 1134 1126
# Does one month has a mean of 981?
visits2016_mean <- map(visits2016, mean)
has_element(visits2016_mean,981)
TRUE
Functional Programming ระดับกลางด้วย purrr

มาฝึกกันเถอะ!

Functional Programming ระดับกลางด้วย purrr

Preparing Video For Download...