【问题标题】:Binning by Subgroup in R在 R 中按子组分箱
【发布时间】:2020-05-13 01:18:03
【问题描述】:

我有一个包含市场、零售商和销售的数据框。我需要将每个市场中的零售商分成 5 个分位数。

例子:

dataframe <- structure(list(Market = c(1, 1, 1, 2, 2, 2), Retailer = c(1, 
2, 3, 4, 5, 6), Sales = c(5, 10, 25, 5, 10, 25), Quantile = c(1, 
2, 3, 1, 2, 3)), class = "data.frame", row.names = c(NA, -6L))

【问题讨论】:

  • 您可以将tapply 与FUN = cut 和breaks = quantile(x, probs=seq(0,1,1/5)) 一起使用。不过,您应该 dput 您的数据。
  • 请使用dput添加数据,而不是图片。还显示相同的预期输出。请阅读有关how to ask a good question 的信息以及如何提供reproducible example

标签: r grouping binning


【解决方案1】:

一种方法是使用来自dplyrgroup_byntile

library(dplyr)
dataframe %>%
  group_by(Market) %>%
  mutate(Quantile = ntile(Sales, 4))
# A tibble: 150 x 4
# Groups:   Market [3]
   Market Retailer Sales Quantile
    <int>    <int> <dbl>    <int>
 1      1        1 16804        1
 2      1        2 80752        4
 3      1        3 38494        2
 4      1        4 32773        2
 5      1        5 60210        3
# … with 145 more rows

数据

set.seed(3)
dataframe <- data.frame(Market = rep(1:3, each = 50), 
                        Retailer = rep(1:50, times = 3), 
                        Sales = round(runif(150,0,100000),0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-22
    • 2016-09-14
    • 2017-09-12
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多