將連續變數轉為類別變數(2)
先前轉換的一個特例,是依變數的分位數把連續變數切成分箱。這種作法常用來分析問卷回覆或評分。如果你要受訪者從 1 到 5 顆星進行評分,中位數不一定會是 3 星。這時,把分數依分位數分組會很有幫助。舉例來說,你可以在第 0、20、40、60、80、100 百分位切分,形成 5 組五等分群。
在 base R 中可以用 cut() 搭配 quantile() 完成。sparklyr 中的對應做法是使用轉換 ft_quantile_discretizer()。它有一個 num_buckets 參數,用來決定分箱數量。以下並列示範 base R 與 sparklyr 的計算方式。和前面一樣,設定 right = FALSE 與 include.lowest。
survey_response_group <- cut(
survey_score,
breaks = quantile(survey_score, c(0, 0.25, 0.5, 0.75, 1)),
labels = c("hate it", "dislike it", "like it", "love it"),
right = FALSE,
include.lowest = TRUE
)
survey_data %>%
ft_quantile_discretizer("survey_score", "survey_response_group", num_buckets = 4)
和 ft_bucketizer() 一樣,分箱結果會是從 0 開始計數的數字。如果你要在 R 中操作,請明確轉換為 factor。
本練習屬於課程
使用 R 的 sparklyr:Spark 入門
練習說明
已為你建立名為 spark_conn 的 Spark 連線。連到 Spark 中曲目中繼資料的 tibble 已預先定義為 track_metadata_tbl。duration_labels 是描述時間長度的字元向量。
- 從
track_metadata_tbl建立名為familiarity_by_duration的變數。- 選取
duration與artist_familiarity欄位。 - 使用
ft_quantile_discretizer()以duration的 5 個分位分箱建立新欄位duration_bin。 - 收集結果。
- 將
duration_bin欄位轉成帶有標籤duration_labels的 factor。
- 選取
- 繪製
artist_familiarity依duration_bin的ggplot()盒狀圖。ggplot()的第一個引數是資料,也就是familiarity_by_duration。ggplot()的第二個引數是美術對應(aesthetic),在aes()中放入duration_bin與artist_familiarity。- 加上
geom_boxplot()繪出盒狀圖。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# track_metadata_tbl, duration_labels have been pre-defined
track_metadata_tbl
duration_labels
familiarity_by_duration <- track_metadata_tbl %>%
# Select duration and artist_familiarity
___ %>%
# Bucketize duration
___ %>%
# Collect the result
___ %>%
# Convert duration bin to factor
___
# Draw a boxplot of artist_familiarity by duration_bin
ggplot(___, aes(___, ___)) +
___()