1. Predicates
For the last lesson of this chapter, we'll focus on predicates.
2. What is a predicate?
Predicates are functions that returns either TRUE or FALSE after testing for a condition.
For example, is.numeric() is a predicate, as it tests if an object is numeric, and returns either TRUE or FALSE, depending on the class of the input.
3. What is a predicate functional?
A predicate functional is a function that takes an object and a predicate function, and does something with these two inputs, for example, keeping the elements, or determining if every element or only some elements of the object meet the condition defined by the predicate.
In the previous lesson, we saw keep() and discard(), which are functionals, as they behave like this.
keep() takes a list, a vector, or a dataframe, and a predicate. It keeps all the elements that return TRUE when tested against the predicate.
4. every() and some()
With the every() and some() functions, we are testing if every or some elements of the object satisfy the condition.
This condition can be an already known function, like as.numeric(), or it can be a mapper, like the one we are creating here.
5. detect_index()
detect_index() returns the first element that satisfies the condition.
Let's go through the code on the slide. The first code block returns the index of the first element in the visits2016 list with a mean over 1000. The second code block returns the index of the last element that satisfies this condition.
6. has_element() and detect()
If you pass .right = TRUE, the index of the last element that satisfies it is returned. detect(), alone, returns the value, not the index. As you can see on the slide, the code does not return the index, but the value of the element.
has_element() tests if an object contains specific elements. The second code block test if at least one month has a mean equal to 981.
7. Let's practice!
Let finish this first chapter by using predicates!