[英]ntile() equivalent for equal ranges
我想將數據框的一列拆分為相同大小的箱。 例如,我可以看一個向量
# I know it's also possible to use base cut though I always found that ugly
library(dplyr)
library(purrr)
library(magrittr)
set.seed(1234)
bins <- 4
vec <- sample(1:100, 20)
binsize <- (max(vec) - min(vec)) / bins
bin_limits <- binsize * 1:bins + min(vec)
equi_range_ntiles <- map_dbl(vec, function(x, lims = bin_limits) min(which(x <= lims)))
equi_range_ntiles
c.f. 我不想要的是相同大小的組,例如
ntiles <- ntile(vec, bins)
ntiles
如果有一種有效且干凈的方法來做到這一點,我將不勝感激。 從向量我可能可以概括它,但為了增加上下文,我的實際用例更類似於
df <- data.frame(
grouping = sample(1:2, 20, replace = TRUE),
val = sample(1:100, 20)
)
df_ntiles <- df %>%
group_by(grouping) %>%
mutate(ntile = ntile(val, bins))
我使用第一節中等效的 function 而不是ntile
。 這可能是最干凈的方法就是將我的代碼從第一部分包裝到 function 並應用它,但如果沒有內置的東西我會感到驚訝
您可以使用我的 package:
library(santoku)
vec <- sample(1:100, 20)
chop_evenly(vec, 10) # for 10 groups
[1] [4, 13.5) [42, 51.5) [32.5, 42) [70.5, 80) [70.5, 80) [89.5, 99]
[7] [51.5, 61) [89.5, 99] [89.5, 99] [4, 13.5) [32.5, 42) [42, 51.5)
[13] [4, 13.5) [13.5, 23) [4, 13.5) [13.5, 23) [23, 32.5) [32.5, 42)
[19] [61, 70.5) [80, 89.5)
10 Levels: [4, 13.5) [13.5, 23) [23, 32.5) [32.5, 42) [42, 51.5) ... [89.5, 99]
chop_evenly(vec, 4)
[1] [4, 27.75) [27.75, 51.5) [27.75, 51.5) [51.5, 75.25) [51.5, 75.25)
[6] [75.25, 99] [51.5, 75.25) [75.25, 99] [75.25, 99] [4, 27.75)
[11] [27.75, 51.5) [27.75, 51.5) [4, 27.75) [4, 27.75) [4, 27.75)
[16] [4, 27.75) [27.75, 51.5) [27.75, 51.5) [51.5, 75.25) [75.25, 99]
Levels: [4, 27.75) [27.75, 51.5) [51.5, 75.25) [75.25, 99]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.