Intermediate Functional Programming with purrr
Colin Fay
Data Scientist & R Hacker at ThinkR
Predicates: return TRUE or FALSE
is.numeric()
, %in%
, is.character()
, etc.
is.numeric(10)
TRUE
Predicate functionals:
keep(airquality, is.numeric)
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
# 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
# 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