Astuces pour fct_relevel()
Dans l’exercice précédent, il fallait écrire le nom de chaque niveau pour réordonner explicitement le facteur. Mais parfois, vous avez de nombreux niveaux et vous ne souhaitez en déplacer qu’un seul. Plutôt que de tout réécrire, vous pouvez utiliser certains arguments utilitaires de fct_relevel() pour vous faire gagner du temps. Essayons-les sur la variable FormalEducation dans multiple_choice_responses ; affichez les niveaux de multiple_choice_responses$FormalEducation dans la console pour commencer.
Cet exercice fait partie du cours
Données catégorielles dans le Tidyverse
Instructions
- En trois appels à mutate, modifiez
FormalEducationde la façon suivante :- Placez « I did not complete any formal education past high school » et « Some college/university study without earning a bachelor's degree » au début.
- Placez « I prefer not to answer » en dernier niveau.
- Placez « Doctoral degree » en sixième niveau (après le cinquième niveau).
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
multiple_choice_responses %>%
# Move "I did not complete any formal education past high school" and "Some college/university study without earning a bachelor's degree" to the front
mutate(FormalEducation = fct_relevel(FormalEducation, ___, "Some college/university study without earning a bachelor's degree")) %>%
# Move "I prefer not to answer" to be the last level.
mutate(FormalEducation = fct_relevel(FormalEducation, ___, after = Inf)) %>%
# Move "Doctoral degree" to be after the 5th level
mutate(FormalEducation = fct_relevel(FormalEducation, ___, ____)) %>%
# Examine the new level order
pull(FormalEducation) %>%
levels()