取得層級數量
在 dplyr 中使用 mutate() 和 summarize() 時,你可以用 across() 指定:當第一個引數條件成立時,把第二個引數(也就是一個函式)套用到所有欄位。
我們會搭配 tidyr 來取得 multiple_choice_responses 中每個因子變數的層級數量。tidyr 的 pivot_longer() 會把資料集從寬格式轉成長格式。它需要兩個引數,分別是新的欄位名稱——一個用來放原本的欄位名稱,另一個用來放所有的值。
本練習屬於課程
Tidyverse 的類別資料
練習說明
- 把所有字元欄位轉成因子欄位,並把新資料集存為
responses_as_factors。 - 建立新資料集
number_of_levels,其中你需要:- 使用
summarize搭配across,對每個欄位套用函式nlevels()。 - 將資料集的格式從寬格式改為長格式。
- 使用
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Change all the character columns to factors
responses_as_factors <- multiple_choice_responses %>%
mutate(___(is.character, as.factor))
number_of_levels <- responses_as_factors %>%
# Apply the function nlevels to each column
summarize(___(everything(), ___)) %>%
# Change the dataset from wide to long
___(everything(), names_to = "variable", values_to = "num_levels")