我有代理商及其相应的售出产品数量的数据框架。
Gent_Code number_policies
A096 3
A0828 12
A0843 2
A0141 2
B079 7
B05 3
M012 5
P010 2
S039 3我想计算每个值( xi )所在的百分位数,以便数据中p%的值低于xi。百分位数的最小值将是0,而最大值将非常接近1,而不是1。
我做了以下工作:
ag_df <- mutate(ag_df, pon_percentiles = ecdf(ag_df$pon)(ag_df$pon))
summary(ag_df$pon_percentiles )
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.4805 0.4805 0.6417 0.6356 0.7738 1.0000 但是,我希望百分位数公式的计算低于某个值,而不是低于或等于该值。
因此,向量中最小值的百分位数的值应该是0,而最大值的百分位数应该接近于1,而不是恰好是1。
Current output:
0.6666667 1.0000000 0.3333333 0.3333333 0.8888889 0.6666667 0.7777778 0.3333333 0.6666667如果我们看到上面的输出,number_policies (2)的min的值是0.3333,但我希望它是0。对于max为12,它不应该是1,而应该是0.99。
我如何在R中做到这一点?我在基本函数中搜索了相关参数,如ecdf、cume_distr等,但没有找到任何相关参数。有人能帮我一下吗?
发布于 2019-11-23 17:51:16
使用percent_rank()函数的一种解决方案是:
pkgs <- c("tidyverse", "stringi")
invisible(lapply(pkgs, require, character.only = TRUE))
set.seed(2)
n <- 30
db <- tibble(gent_code = paste0(stri_rand_strings(n, 1, '[A-Z]'),
stri_rand_strings(n, 4, '[0-9]')),
nr_pol = sample(1L:100L, n, TRUE))
db %>%
mutate(percentile = percent_rank(nr_pol)) %>%
print(n = n)它给出了输出:
gent_code nr_pol percentile
<chr> <int> <dbl>
1 E0188 35 0.241
2 S5682 91 0.862
3 O6192 96 0.931
4 E1197 97 1.000
5 Y9358 39 0.345
6 Y0069 63 0.552
7 D2879 14 0.138
8 V6778 25 0.172
9 M6284 75 0.759
10 O3420 69 0.690
11 O2301 35 0.241
12 G1728 3 0.0345
13 T4536 38 0.310
14 E0418 1 0
15 K9373 44 0.414
16 W9335 66 0.621
17 Z4140 58 0.448
18 F1424 62 0.517
19 L9825 96 0.931
20 B8411 59 0.483
21 R0735 41 0.379
22 K8881 81 0.793
23 V9502 87 0.828
24 D9827 5 0.0690
25 J5363 8 0.103
26 M2909 68 0.655
27 D3658 94 0.897
28 J1312 34 0.207
29 Z6347 63 0.552
30 D6342 72 0.724 正如您所看到的,它从0开始,但最高百分位数将等于1,因为它反映了数据中最高数量的策略。
编辑:在这种情况下,强制12等于第99个百分位数,这意味着数据中的数据点高于12。它将等于1,因为您所有的数据点都小于或等于这个值。
发布于 2019-11-23 16:13:19
您可以简单地通过分位数函数来完成此操作:
quantile(df, probs = c(0, 0.24, 0.49, 0.74, 0.99))希望这能有所帮助!
发布于 2019-11-23 22:40:20
我想这就是你想要的,但我不确定,你只需要按照你想要的方式设置labels和probs即可。
iris2 <- iris
iris2$quartile_number <- cut(iris$Sepal.Length,
quantile(iris$Sepal.Length) ,
include.lowest=T,
labels=c(.25, .5, .75, 1))
head(iris2)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species quartile_number
1 5.1 3.5 1.4 0.2 setosa 0.25
2 4.9 3.0 1.4 0.2 setosa 0.25
3 4.7 3.2 1.3 0.2 setosa 0.25
4 4.6 3.1 1.5 0.2 setosa 0.25
5 5.0 3.6 1.4 0.2 setosa 0.25
6 5.4 3.9 1.7 0.4 setosa 0.5https://stackoverflow.com/questions/59005574
复制相似问题