Trik fct_relevel()
Pada latihan sebelumnya, nama setiap level harus dituliskan untuk mengubah urutan faktor secara eksplisit. Namun, terkadang Anda memiliki banyak level dan hanya perlu memindahkan satu. Alih-alih menuliskan semua level, Anda dapat menggunakan beberapa argumen pembantu di fct_relevel() untuk menghemat pengetikan. Mari coba beberapa di antaranya pada variabel FormalEducation di multiple_choice_responses; lihat level dari multiple_choice_responses$FormalEducation di konsol untuk memulai.
Latihan ini adalah bagian dari kursus
Data Kategorikal di Tidyverse
Petunjuk latihan
- Dalam tiga pemanggilan mutate, ubah
FormalEducationdengan cara berikut:- Pindahkan "I did not complete any formal education past high school" dan "Some college/university study without earning a bachelor's degree" ke bagian depan.
- Pindahkan "I prefer not to answer" menjadi level terakhir.
- Pindahkan "Doctoral degree" menjadi level keenam (setelah level kelima).
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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()