我希望使用 tidyverse 离散化数值数据,目的是使用条形图绘制不同的数值范围,就好像数据是分类的一样,通过手动声明切割发生的位置,例如年龄组或收入范围。我希望间隔宽度不等。
到目前为止,我已经尝试了基本的 R 方法,使用 cut()
并使用 breaks = c()
设置 bin。但是,我注意到 ggplot2
包中存在一组函数 cut_interval
、cut_width
和 cut_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 创建于 2019-06-03 (v0.2.1)
上面的内容接近我想要的,但是它根据间隔数设置了中断。
在上面的例子中,我希望我的分组完全如下:
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
关于r - Tidyverse : Converting numerical data into categorical data for plotting with uneven bin width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432562/