首页 > 解决方案 > 如何根据 R 中的另一个现有表得出百分位数

问题描述

我有以下收入百分比分布,产品:

Percentile  Revenue Prod
0           344     1
0.1         10000   1
0.2         15413   1
0.3         19918   1
0.4         28729   2
0.5         41136   2
0.6         60000   3
0.7         90429   5
0.8         125684  7
0.9         202231  10
1           3515000 80

对于以下记录,需要从上述分布派生两个指标 - rev_percentile 和 prod_percentile:

Code    Revenue prod freq
A6696   57657   3       3
A6828   184552  12      4
A843    101632  2       2
A141    58551   2       2
B579    166668  7       6
B625    98641   3       3
M257    92664   5       4
P50     12173   2       2
S339    81494   3       3
S06283  100290  4       2

因此,例如,对于代码 A6696,rev_percentile 的值是 0.6,prod_percentile 也是 0.6。同样,对于第二个代码,两个值都是 0.9。

有人可以帮我在 R 中实现这个吗?

标签: r

解决方案


我们可以在这里使用cutfindInterval将数据分组。

df$rev_percentile <- perct_tab$Percentile[findInterval(df$Revenue,c(0, perct_tab$Revenue))]
df$prod_percentile <- perct_tab$Percentile[findInterval(df$prod, perct_tab$Prod)]
df

#     Code Revenue prod freq rev_percentile prod_percentile
#1   A6696   57657    3    3            0.6             0.6
#2   A6828  184552   12    4            0.9             0.9
#3    A843  101632    2    2            0.8             0.5
#4    A141   58551    2    2            0.6             0.5
#5    B579  166668    7    6            0.9             0.8
#6    B625   98641    3    3            0.8             0.6
#7    M257   92664    5    4            0.8             0.7
#8     P50   12173    2    2            0.2             0.5
#9    S339   81494    3    3            0.7             0.6
#10 S06283  100290    4    2            0.8             0.6

数据

df <- structure(list(Code = structure(c(2L, 3L, 4L, 1L, 5L, 6L, 7L, 
8L, 10L, 9L), .Label = c("A141", "A6696", "A6828", "A843", "B579", 
"B625", "M257", "P50", "S06283", "S339"), class = "factor"), 
Revenue = c(57657L, 184552L, 101632L, 58551L, 166668L, 98641L, 
92664L, 12173L, 81494L, 100290L), prod = c(3L, 12L, 2L, 2L, 
7L, 3L, 5L, 2L, 3L, 4L), freq = c(3L, 4L, 2L, 2L, 6L, 3L, 
4L, 2L, 3L, 2L)), class = "data.frame", row.names = c(NA, -10L))

perct_tab <- structure(list(Percentile = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 
0.7, 0.8, 0.9, 1), Revenue = c(344L, 10000L, 15413L, 19918L, 
28729L, 41136L, 60000L, 90429L, 125684L, 202231L, 3515000L), 
Prod = c(1L, 1L, 1L, 1L, 2L, 2L, 3L, 5L, 7L, 10L, 80L)), class = 
"data.frame", row.names = c(NA, -11L))

推荐阅读