Split up with keep() and discard()
We want to split our results into two groups: the days over 100, and the days under 100. We'll combine keep()
and discard()
to do so.
Why two functions? Couldn't we use one function? Couldn't we create a mapper called is_less_than_hundred
?
We could, but that would be more error-prone: it's easier to switch from
keep()
todiscard()
than copying and pasting. By combining both functions, we only need one mapper. That means that if we want to change the threshold, we'll only need to do it once, not twice, as we would have to do if we had two mappers.
This is a rule you should endeavor to apply when coding: write code so that if you need to change one thing, you will have to change it just once.
all_visits
is still available in your workspace.
This exercise is part of the course
Intermediate Functional Programming with purrr
Exercise instructions
- Map the
set_names()
function onall_visits
to add the name of the days:all_visits_named
. - Create a mapper called
threshold
that will test if.x
is over 100. - Create
group_over
by keeping the elements that are over 100. - Create
group_under
by discarding the elements that are over 100.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Set the name of each subvector
day <- c("mon", "tue", "wed", "thu", "fri", "sat", "sun")
all_visits_named <- ___(all_visits, ~ ___(.x, ___))
# Create a mapper that will test if .x is over 100
threshold <- ___
# Run this mapper on the all_visits_named object: group_over
group_over <- ___(all_visits_named, ~ ___(.x, ___))
# Run this mapper on the all_visits_named object: group_under
group_under <- ___(all_visits_named, ~ ___(.x, ___))