Chr*_* A. 3 r continuous ggplot2 categorical-data
使用 tidyverse,我希望通过手动声明削减发生的位置(例如年龄组或收入范围)来离散化数值数据,目的是使用条形图绘制不同的数值范围,就好像数据是分类的一样。我希望有不等宽度的间隔。
到目前为止,我已经尝试了基本的 R 方法,cut()使用breaks = c(). 然而,我注意到包中存在一组函数cut_interval、cut_width、 和。我认为有一种方法可以使用这些函数手动设置间隔切割,因为间隔和数字变量存在参数。cut_numberggplot2breaks
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.
Run Code Online (Sandbox Code Playgroud)
由reprex 包(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)
Run Code Online (Sandbox Code Playgroud)
这会给你:
# 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4714 次 |
| 最近记录: |