title: calculating n quantiles by group in tidyverse
body: <p>I have a unique problem where I would like to add a column of percentiles for each group in a data frame. Here is how my data look like:</p>
  <pre><code>library(tidyverse)
  set.seed(123)
  
  df &lt;- tibble(id = 1:100, 
                   group = rep(letters[1:4], 25), 
                   x = c(sample(1:100, 25, replace = T),
                         sample(101:200, 25, replace = T),
                         sample(201:300, 25, replace = T),
                         sample(301:400, 25, replace = T)))
  
  &gt; df
  # A tibble: 100 x 3
        id group     x
     &lt;int&gt; &lt;chr&gt; &lt;int&gt;
   1     1 a        78
   2     2 b        80
   3     3 c         7
   4     4 d       100
   5     5 a        45
   6     6 b        76
   7     7 c        25
   8     8 d        91
   9     9 a        13
  10    10 b        84
  # ... with 90 more rows
  
  # Function to create a table ten percentiles for a numeric vector
  percentiles_table &lt;- function(x) {
    res &lt;- round(quantile(x, probs = seq(from=.1, to=1, by=0.1)), 0)
    res &lt;- data.frame(percentile = names(res), to = res )
    res &lt;- res %&gt;% 
      mutate(from = lag(to, default = 0)) %&gt;% 
      select(from,to,percentile)
  }
  
  # Table of percentiles
  percentiles &lt;- df %&gt;% 
    group_by(group) %&gt;% 
    summarise(percentiles_table(x)) %&gt;% 
    ungroup()
  
  &gt; percentiles
  # A tibble: 40 x 4
     group  from    to percentile
     &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt;     
   1 a         0    25 10%       
   2 a        25    71 20%       
   3 a        71   106 30%       
   4 a       106   125 40%       
   5 a       125   198 50%       
   6 a       198   236 60%       
   7 a       236   278 70%       
   8 a       278   325 80%       
   9 a       325   379 90%       
  10 a       379   389 100%   
  </code></pre>
  <p>I would like to add the <code>percentile</code> column to df for each group where the value of <code>x</code> falls between <code>from</code> and <code>to</code>.</p>
  <p>There might be some way to calculate the <code>percentile</code> column directly without having it calculated in a separated <code>data.frame</code> and then appending it back to <code>df</code>.</p>