연속형 변수를 범주형으로 변환하기 (2)
앞선 변환의 특별한 경우로, 연속형 변수를 그 변수의 분위수로 정의된 구간(buckets)으로 나누는 방법이 있습니다. 이 변환은 설문 응답이나 리뷰 점수를 분석할 때 자주 사용돼요. 예를 들어 별점 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에 저장된 트랙 메타데이터에 연결된 티블 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로 변환하세요.
duration_bin별artist_familiarity의ggplot()박스플롯을 그리세요.ggplot()의 첫 번째 인자는 데이터인familiarity_by_duration입니다.ggplot()의 두 번째 인자는 미학 매핑으로,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(___, ___)) +
___()