Quartiles by group saved as new variable in data frame
<p>I have data that look something like this:</p>

<pre><code>id &lt;- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9)
yr &lt;- c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)
gr &lt;- c(3,4,5,3,4,5,3,4,5,4,5,6,4,5,6,4,5,6,5,6,7,5,6,7,5,6,7)
x &lt;- c(33,48,31,41,31,36,25,38,28,17,39,53,60,60,19,39,34,47,20,28,38,15,17,49,48,45,39)
df &lt;- data.frame(id,yr,gr,x)

   id yr gr  x
1   1  1  3 33
2   1  2  4 48
3   1  3  5 31
4   2  1  3 41
5   2  2  4 31
6   2  3  5 36
7   3  1  3 25
8   3  2  4 38
9   3  3  5 28
10  4  1  4 17
11  4  2  5 39
12  4  3  6 53
13  5  1  4 60
14  5  2  5 60
15  5  3  6 19
16  6  1  4 39
17  6  2  5 34
18  6  3  6 47
19  7  1  5 20
20  7  2  6 28
21  7  3  7 38
22  8  1  5 15
23  8  2  6 17
24  8  3  7 49
25  9  1  5 48
26  9  2  6 45
27  9  3  7 39
</code></pre>

<p>I would like to create a new variable in the data frame that contains the quantiles of "x" computed within each unique combination of "yr" and "gr". That is, rather than finding the quantiles of "x" based on all 27 rows of data in the example, I would like to compute the quantiles by two grouping variables: yr and gr. For instance, the quantiles of "x" when yr = 1 and gr = 3, yr = 1 and gr = 4, etc.</p>

<p>Once these values are computed, I would like them to be appended to the data frame as a single column, say "x_quant". </p>

<p>I am able to split the data into the separate groups I need, and I am know how to calculate quantiles, but I am having trouble combining the two steps in a way that is amenable to creating a new column in the existing data frame.</p>

<p>Any help y'all can provide would be greatly appretiated! Thank you much!</p>

<p>~kj</p>