Tidyverse:将数值数据转换为分类数据以绘制不均匀的 bin 宽度

Tidyverse: Converting numerical data into categorical data for plotting with uneven bin width

我希望使用 tidyverse 来离散化数值数据,目的是使用条形图绘制不同的数值范围,就好像数据是分类的一样,通过手动声明切割发生的位置,例如年龄群体或收入范围。我希望间隔宽度不等。

到目前为止,我已经尝试了基本的 R 方法,使用 cut() 并使用 breaks = c() 设置 bin。但是,我注意到 ggplot2 包中存在一组函数 cut_intervalcut_widthcut_number。我认为有一种方法可以使用这些函数手动设置间隔切割,因为间隔和数字变量存在 breaks 参数。

library(tidyverse)

mtcars <- as_tibble(mtcars)

mtcars %>% 
  count(cut_interval(mpg, n = 4))
#> # A tibble: 4 x 2
#>   `cut_interval(mpg, n = 4)`     n
#>   <fct>                      <int>
#> 1 [10.4,16.3]                   10
#> 2 (16.3,22.1]                   13
#> 3 (22.1,28]                      5
#> 4 (28,33.9]                      4

mtcars %>% 
  count(cut_interval(mpg, n = 4, breaks = c(10, 18, 23, 28, 35)))
#> Error: Evaluation error: lengths of 'breaks' and 'labels' differ.

reprex package (v0.2.1)

于 2019-06-03 创建

以上接近我想要的,但它根据间隔数设置中断。

在上面的例子中,我希望我的分组精确如下:

10-18、19-23、24-28、29-35。

是否可以使用 breaks 参数?谢谢。

您可以只使用实际的基础 cut 函数来执行此操作:

library(tidyverse)

mtcars %>% 
    mutate(bin = cut(mpg, breaks = c(Inf, 10, 18, 19, 23, 24, 28, 29,35))) %>% 
    count(bin)

哪个会给你:

# A tibble: 5 x 2
  bin         n
  <fct>   <int>
1 (10,18]    13
2 (18,19]     2
3 (19,23]    10
4 (24,28]     3
5 (29,35]     4