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 devez en déplacer qu'un seul. Plutôt que d'écrire tous les niveaux, vous pouvez utiliser des arguments d'aide dans fct_relevel() pour vous éviter de la saisie. Essayons-en quelques-uns sur la variable FormalEducation dans multiple_choice_responses; affichez les niveaux de multiple_choice_responses$FormalEducation dans la console pour commencer.
Cette activité fait partie du cours
Données catégorielles dans le tidyverse
Instructions de l’exercice
- En trois appels à mutate, modifiez
FormalEducationcomme suit :- Dé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.
- Déplacez « I prefer not to answer » pour qu'il soit le dernier niveau.
- Déplacez « Doctoral degree » pour qu'il devienne le sixième niveau (après le cinquième niveau).
Exercice interactif pratique
Essayez cet exercice en complétant ce code d’exemple.
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()