如何在 r 中按组计算分位数(附示例)


在统计学中,分位数是将分类数据集分为相等组的值。

要计算 R 中按某个变量分组的分位数,我们可以使用 R 中dplyr包中的以下函数:

 library (dplyr)

#define quantiles of interest
q = c(.25, .5, .75)

#calculate quantiles by grouping variable
df %>%
  group_by(grouping_variable) %>%
  summarize(quant25 = quantile (numeric_variable, probs = q[1]), 
            quant50 = quantile (numeric_variable, probs = q[2]),
            quant75 = quantile (numeric_variable, probs = q[3]))

以下示例展示了如何在实践中使用此语法。

示例:R 中按组划分的分位数

以下代码显示了如何计算 R 中数据集按球队分组的获胜次数的分位数:

 library (dplyr)

#create data
df <- data. frame (team=c('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
                        'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B',
                        'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'),
                 wins=c(2, 4, 4, 5, 7, 9, 13, 13, 15, 15, 14, 13,
                        11, 9, 9, 8, 8, 16, 19, 21, 24, 20, 19, 18))

#view first six rows of data
head(df)

  team wins
1 TO 2
2 to 4
3 to 4
4 to 5
5 TO 7
6 to 9

#define quantiles of interest
q = c(.25, .5, .75)

#calculate quantiles by grouping variable
df %>%
  group_by(team) %>%
  summarize(quant25 = quantile (wins, probs = q[1]), 
            quant50 = quantile (wins, probs = q[2]),
            quant75 = quantile (wins, probs = q[3]))

  team quant25 quant50 quant75           
1 to 4 6 10  
2 B 9 12 14.2
3 C 17.5 19 20.2

请注意,我们还可以指定所需的任意数量的分位数:

 #define quantiles of interest
q = c(.2, .4, .6, .8)

#calculate quantiles by grouping variable
df %>%
  group_by(team) %>%
  summarize(quant20 = quantile (wins, probs = q[1]), 
            quant40 = quantile (wins, probs = q[2]),
            quant60 = quantile (wins, probs = q[3]),
            quant80 = quantile (wins, probs = q[4]))

  team quant20 quant40 quant60 quant80
              
1 to 4 4.8 7.4 11.4
2 B 9 10.6 13.2 14.6
3 C 16.8 18.8 19.2 20.6

您还可以选择计算每组的单个分位数。例如,以下是计算每支球队获胜次数的第 90 个百分位的方法:

 #calculate 90th percentile of wins by team
df %>%
  group_by(team) %>%
  summarize(quant90 = quantile (wins, probs = 0.9 ))

   team quant90
     
1 to 13  
2 B 15  
3 C 21.9

其他资源

如何在 R 中计算四分位数
如何在 R 中计算十分位数
如何在 R 中计算百分位数

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注