如何在dplyr和group_by中使用分位数 [英] How to use quantile with dplyr and group_by

查看:215
本文介绍了如何在dplyr和group_by中使用分位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有此代码。我尝试使用分位数,然后按组(年份,其中有两个)进行子集划分。我想我可以使用 dplyr 来做到这一点,但是它不起作用:

I have this code below. I'm trying to use quantiles and then subset by groups (years, of which there are two). I think I can do this with dplyr, but it is not working:

Claims6 %>% 
  group_by(year) %>% 
  summarise(ranker = quantile(Expense, prob = c(.10, .30, .50, .80)))


推荐答案

您可以使用 do 函数可解决此类问题。我生成了一些数据供您测试。

You can use the do function for problems like this. I generated some data for you to test this out.

library(dplyr)
Claims6 <- data.frame(year = factor(rep(c(2015, 2016), each = 10)),
                  Expense = runif(20))

Claims6 %>% group_by(year) %>% 
  do(data.frame(t(quantile(.$Expense, probs = c(0.10, 0.30, 0.50, 0.80)))))


Source: local data frame [2 x 5]
Groups: year [2]

    year       X10.      X30.      X50.      X80.
  (fctr)      (dbl)     (dbl)     (dbl)     (dbl)
1   2015 0.06998258 0.2855598 0.5469119 0.9499181
2   2016 0.22983539 0.3691736 0.4754915 0.7058695

这篇关于如何在dplyr和group_by中使用分位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆