Grouped table of percentiles [duplicate]

本小妞迷上赌 提交于 2020-05-17 06:44:47

问题


I need to calculate which value represents the 5%, 34%, 50%, 67% and 95% percentile within the group (in separate columns). An expected output would be

    5%   34%  50%  67% 95%
A   4     6    8    12  30
B   1     2    3    4    10

for integer values for each group.

The code below shows what I have so far (but using generated data):

library(dplyr)
library(tidyr)
data.frame(group=sample(LETTERS[1:5],100,TRUE),values=rnorm(100)) %>%
      group_by(group) %>%
      mutate(perc_int=findInterval(values, 
                    quantile(values, probs=c(0.05,0.34,0.5,0.67,0.95)))) %>%
      pivot_wider(names_from = perc_int,values_from = values)

I get six colums using this example, and I am not sure why.

Also, the columns are filled with a vector and not the single value. How do I get just a single value representing the percentile in the value vector?


回答1:


You could get the quantile data in a list and then use unnest_wider to have separate columns.

library(dplyr)
set.seed(123)

data.frame(group=sample(LETTERS[1:5],100,TRUE),values=rnorm(100)) %>%
   group_by(group) %>%
   summarise(perc_int= list(quantile(values, probs=c(0.05,0.34,0.5,0.67,0.95)))) %>%
   tidyr::unnest_wider(perc_int)

# A tibble: 5 x 6
#  group   `5%`  `34%`   `50%` `67%` `95%`
#  <fct>  <dbl>  <dbl>   <dbl> <dbl> <dbl>
#1  A     -2.40  -0.580 -0.0887 0.371  1.38
#2  B     -1.83  -0.200  0.0848 0.546  1.78
#3  C     -0.947 -0.148  0.184  0.789  1.81
#4  D     -0.992 -0.275 -0.0193 0.274  1.82
#5  E     -1.65  -0.457 -0.0422 0.540  1.66



回答2:


The following should work.

library(dplyr)
data.frame(group=sample(LETTERS[1:5],100,TRUE),values=rnorm(100)) %>%
      group_by(group) %>% summarise(`5 %` = quantile(values,0.05),
                                    `34 %` = quantile(values,0.34), 
                                    `50 %` = quantile(values,0.5), 
                                    `67 %` = quantile(values,0.67), 
                                    `95 %` = quantile(values,0.95))


来源:https://stackoverflow.com/questions/59916760/grouped-table-of-percentiles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!