Format labels produced by cut() as percentages

后端 未结 6 1959
失恋的感觉
失恋的感觉 2021-02-05 10:21

I need to apply cut on a continuous variable to show it with a Brewer color scale in ggplot2, as in Setting breakpoints for data with scale_fill_brewer() function i

6条回答
  •  悲&欢浪女
    2021-02-05 10:31

    My package cutr does very similar things to @krlmlr's function (that I didn't know up until now).

    cutf is just cut with a format_fun argument, and ... which is passed to format_fun, not cut as incut_format.

    smart_cut has more features and different defaults :

    devtools::install_github("moodymudskipper/cutr")
    library(cutr)
    
    x <- seq(0.1, 0.9, by = 0.2)
    breaks <- seq(0, 1, by = 0.25)
    
    cutf(x, breaks, format_fun = scales::percent)
    # [1] (0%,25%]   (25%,50%]  (25%,50%]  (50%,75%]  (75%,100%]
    # Levels: (0%,25%] (25%,50%] (50%,75%] (75%,100%]
    
    smart_cut(x, breaks, format_fun = scales::percent,simplify = F, closed = "right")
    # [1] [0%,25%]   (25%,50%]  (25%,50%]  (50%,75%]  (75%,100%]
    # Levels: [0%,25%] < (25%,50%] < (50%,75%] < (75%,100%]
    

    Hmisc::cut2 now also has a formatfun argument :

    library(Hmisc)
    Hmisc::cut2(x, breaks, formatfun = scales::percent)
    # [1] [0%,25%)   [25%,50%)  [50%,75%)  [50%,75%)  [75%,100%]
    # Levels: [0%,25%) [25%,50%) [50%,75%) [75%,100%]
    

提交回复
热议问题