fct_relevel() の小ワザ
前の演習では、因子の並び替えを明示するために各レベル名をすべて書き出しました。しかし、レベルが多くて一部だけを動かしたいこともあります。そんなときは、fct_relevel() の補助的な引数を使うと入力を減らせます。multiple_choice_responses の変数 FormalEducation で試してみましょう。まずはコンソールで multiple_choice_responses$FormalEducation のレベルを確認してください。
この演習はコースの一部です
tidyverse で学ぶカテゴリ型データ
演習の手順
- 3 回の mutate 呼び出しで、
FormalEducationを次のように変更してください。- "I did not complete any formal education past high school" と "Some college/university study without earning a bachelor's degree" を先頭に移動する。
- "I prefer not to answer" を最後のレベルに移動する。
- "Doctoral degree" を6番目のレベル(5番目の後)に移動する。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
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()