簡體   English   中英

匯總到各個存儲桶后,R個分位數相等的存儲桶

[英]R quantile equal sized bucket after summarizing to the buckets

求和后如何使每個組的大小相等?

以下是將數量分為10組的示例,每組中的項目數相同。

    set.seed(42)
    quantity <- c(runif(100, 0, 100))
    dat <- data.frame(
      qty = quantity,
      qtile = cut(quantity, quantile(quantity, seq(0, 1, 0.1)), 
      include.lowest = TRUE))
    dat <- dat %>% group_by(qtile) %>% summarise(qty = sum(qty))
    ggplot(dat, aes(qtile, qty)) + geom_bar(stat = 'identity')

但是,如何對組進行排序,以使在summarise步驟中, qty變量按組大致相等?

因此,在這個例子中,總qty5244.787 ,每個小組將有524.4787summarise

這是我所能達到的。 我覺得它適合我的用例。 如果其他人有好的改進想法,請隨時更新答案。

set.seed(42)
quantity <- c(runif(100, 0, 100))

dat <- data.table(
  qty = quantity,
  wt = quantity
)
dat[!is.na(qty), avg := sum(wt) / 10]
setorder(dat, qty, wt)
dat[!is.na(qty), cum_wt := cumsum(wt)]
dat[!is.na(qty), level := cum_wt / avg]
dat[!is.na(qty), qtile := ceiling(level)]

dat <- dat[, .(qty = sum(qty)), by = 'qtile']

ggplot(dat, aes(qtile, qty)) + geom_bar(stat = 'identity')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM