基于观测分布/频率的连续数据分箱来决定分箱范围 r dplyr

问题描述

我现在已经好几天没有运气扫描互联网以寻求有关此问题的帮助。任何建议将不胜感激! (尤其是在 tidyverse 友好的语法中)

我有一个大约。 4300 行/ obs 和 320 列。一列是我的因变量,一个连续的数字列,称为“RR”(响应比率)。我的目标是将 RR 值分为 10 个因子水平。稍后用于机器学习分类

我用这段代码试验了 cut() 函数

df <- era.af.Al_noNaN %>%
  rationalize() %>%
  drop_na(RR) %>%
  mutate(RR_MyQuantile = cut(RR,breaks = unique(quantile(RR,probs = seq.int(0,1,by = 1 / numbers_of_bins))),include.lowest = TRUE)) 

但我没有运气,因为我的箱子在每个箱子中都有相等的 n,但是,这并不能反映数据的分布..我在这里研究了一下https://towardsdatascience.com/understanding-feature-engineering-part-1-continuous-numeric-data-da4e47099a7b,但我根本无法实现在 R 中相同。

Here is the distribution of my RR data values grouped into classes *not what I want

解决方法

您可以尝试使用 hist() 来获得休息时间。它用于绘制直方图,但它也提供其他相关数据作为副作用。在下面的示例中,图被 plot = FALSE 抑制以显示中断数据。然后,在 cut() 中使用它。这应该为您提供截止值,保持变量的分布。

hist(iris$Sepal.Length,breaks = 5,plot = FALSE)
# $breaks
# [1] 4 5 6 7 8
# 
# $counts
# [1] 32 57 49 12
# 
# ...<omitted>

breaks <- hist(iris$Sepal.Length,plot = FALSE)$breaks

dat <- iris %>% 
  mutate(sepal_length_group = cut(Sepal.Length,breaks = breaks))

dat %>% 
  count(sepal_length_group)

#   sepal_length_group  n
# 1              (4,5] 32
# 2              (5,6] 57
# 3              (6,7] 49
# 4              (7,8] 12
,

谢谢!

我还尝试使用 cut() 和 count()。然后我使用 labels=FALSE 来给出标签,这些标签可以在新的变异中使用,用于带有间隔组字符名称的新列..

numbers_of_bins = 10

df <- era.af.Al_noNaN %>%
  rationalize() %>%
  drop_na(RR) %>%
  mutate(RR_MyQuantile = cut(RR,breaks = unique(quantile(RR,probs = seq.int(0,1,by = 1 / numbers_of_bins))),include.lowest = TRUE))

head(df$RR_MyQuantile,10)

df %>% 
  group_by(RR_MyQuantile) %>% 
  count()