Predicates

Intermediate Functional Programming with purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

What is a predicate?

Predicates: return TRUE or FALSE

  • Test for conditions
  • Exist in base R: is.numeric(), %in%, is.character(), etc.

 

is.numeric(10)
TRUE
Intermediate Functional Programming with purrr

What is a predicate functional?

Predicate functionals:

  • Take an element & a predicate
  • Use the predicate on the element

 

keep(airquality, is.numeric)
Intermediate Functional Programming with purrr

every(): does every element satisfy a condition?

# 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(): do some elements satisfy a condition?

# Is the mean of some months above 1000? 
some(visits2016, ~ mean(.x) > 1000)
TRUE
Intermediate Functional Programming with 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
Intermediate Functional Programming with purrr

has_element() and 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
Intermediate Functional Programming with purrr

Let's practice!

Intermediate Functional Programming with purrr

Preparing Video For Download...