【问题标题】:Cutting data into bins, with partitioning, in R在 R 中通过分区将数据切割成箱
【发布时间】:2018-09-10 11:25:31
【问题描述】:

我正在使用 R 中 Hmisc 库函数中的 cut2 将我的数据集切割成固定数量的 bin,例如

library(Hmisc)
as.numeric(cut2(Catchment_Population_Log, g=4))

但是,有没有一种直接的方法来添加一个分区级别,所以我每个类别都有 n 个削减?即,我希望基本上为每个类别独立使用 cut2 (或类似的) (当我在 SQL 中做类似的事情时,我会使用 PARTITION BY)。

所以在我的脑海里,它会是这样的;

as.numeric(cut2(Catchment_Population_Log, g=4, partition_by=CategoryID))

但在 cut2 文档中看不到任何允许这样做的内容。我已经使用 split() 玩过,但一直无法正常工作。

示例数据,包括我希望实现的输出

library(Hmisc)
library(dplyr)
category <- c('Category_1','Category_1','Category_1','Category_1','Category_2','Category_2','Category_2','Category_2','Category_3','Category_3','Category_3','Category_3')
catchment_population_log <- c(0.3,0.2,0.1,0.4,0.4,0.2,0.6,0.9,0.2,0.6,0.2,0.4)
exp_result <- c(2,1,1,2,1,1,2,2,1,2,1,2)
data <- data.frame(category, catchment_population_log)

# Result just using cut2 - data is cut into 2 bins
# based on their catchment_population_log value
data %>%
  mutate(just_using_cut2 = as.numeric(cut2(catchment_population_log,g=2)))

# This time, I'll manually transpose the expected result; each Category 
# should be split into 2 bins based on the catchment_population value 
# independently of each other.
# As a result, a 0.4 value might fall in bin 1 for one category,
# but bin 2 for another category

data %>%
  mutate(just_using_cut2 = as.numeric(cut2(catchment_population_log,g=2))) %>%
  cbind(exp_result)

【问题讨论】:

  • 您可以使用dplyr 进行group_by / mutate / cut,或在base 中使用ave,但请给我们一个可重现的示例。还要在你的问题中加入库调用,cut2 不是基本函数,你可能正在使用Hmisc 所以你需要library(Hmisc)
  • 谢谢 Moody_Mudskipper。是的,我应该包含包裹信息 - 我已经添加了这一点,并将在以后的任何帖子中这样做。我将尝试使用 group_by 和 mutate,看看我如何继续使用它。我还将准备一个可重现的示例。
  • 好的; group_by / mutate / cut 对我的样本数据很有帮助,谢谢!还没有让它在我的实时数据上工作(得到一个breaks are not unique 错误),但让我弄清楚我的数据中有什么问题。
  • 这个错误是因为在某些情况下观察的数量少于我的 bin 数量,所以很容易修复。

标签: r


【解决方案1】:

感谢 Moody_Mudskipper,我能够让它完全按照我的需要工作。

# This works with cut in base, as well as cut2, but I'm using cut2
library(Hmisc)
data %>%
  group_by(category) %>%
  mutate(population_bin = as.numeric(cut2(catchment_population_log,g=2)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2015-04-25
    • 2012-02-13
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多