在dplyr的pipe中,在mutate裡使用cut來將連續變數依據區間分塊,形成新的變數

     本來在dplyr的函數中是不支持cut函數的(cut為R base函數),但將連續變數依照特定區間分塊貼標籤這使用場景太常見了,要把班上成績,依據80,85,90分別給予C,B,A等操作,且在stackover可以看到非常多類似的問題如下:
Create column with grouped values based on another colum

R dplyr – categorize numeric variable with mutate

Is cut() style binning available in dplyr?

cut function not working in dplyr, but works outside

applying cut within dplyr

screenshot.png

cars %>% mutate(type = cut(speed,c(0,15,30),c("slow","fast")))

screenshot.png

發表留言