Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use quantile with dplyr and group_by

Tags:

r

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)))
like image 948
alboman Avatar asked Jun 15 '16 21:06

alboman


1 Answers

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
like image 83
mfidino Avatar answered Oct 11 '22 21:10

mfidino