我正在尝试计算数据框中某个值的百分位排名,并且我也有在数据框中与之相关联的频率进行加权。但我难以想出一种解决方案,可以计算原始值的百分位,就好像整体分布是由该值乘以频率以及其他所有值乘以该频率得到。
例如:
groceries <- tribble(
~item, ~price, ~freq,
"apple", 1, 20,
"banana", 2, 5,
"carrot", 3, 1
)
groceries %>%
mutate(reg_ptile = percent_rank(price),
wtd_ptile = weighted_percent_rank(price, wt = freq))
# the expected result would be:
# A tibble: 3 x 5
item price freq reg_ptile wtd_ptile
<chr> <dbl> <dbl> <dbl> <dbl>
1 apple 1 20 0.0 0.0
2 banana 2 5 0.5 0.8
3 carrot 3 1 1.0 1.0
percent_rank()
是一个实际的dplyr函数。如何编写函数weighted_percent_rank()
?不确定如何在数据框和管道中使用它。如果解决方案也适用于分组,那将是很好的。
编辑:使用uncount()
并不起作用,因为对我使用的数据进行不计数会导致8000亿行。还有其他想法吗?
groceries %>% mutate(prop = freq/sum(freq))
得到的。 - Adhi R.