開始使用免費開始

fct_relevel() 的小技巧

在前一個練習中,你必須把每個層級的名稱都寫出來,才能明確地重新排序 factor。不過有時層級很多,而你只想移動其中一個。這時就不必把所有層級都寫出來,可以在 fct_relevel() 裡使用一些輔助引數,幫你少打一些字。讓我們把這些技巧用在 multiple_choice_responses 中的變數 FormalEducation 上吧;先在主控台檢視 multiple_choice_responses$FormalEducation 的層級作為開始。

本練習屬於課程

Tidyverse 的類別資料

檢視課程

練習說明

  • 透過三個 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()
編輯並執行程式碼