水準数を取得する
dplyr の mutate() と summarize() では、across() を使うと、第1引数の条件に合うすべての列に対して、第2引数で指定した関数を適用できます。
これらと tidyr を組み合わせて、multiple_choice_responses の各ファクター変数について水準の数を求めます。tidyr の pivot_longer() はデータセットをワイド形式からロング形式に変換します。主な2つの引数は新しい列名で、1つは元の列名を、もう1つはすべての値を格納します。
この演習はコースの一部です
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")