ComeçarComece de graça

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() to discard() 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.

Este exercício faz parte do curso

Intermediate Functional Programming with purrr

Ver curso

Instruções do exercício

  • Map the set_names() function on all_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.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

# 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, ___))
Editar e executar o código