title: R Making a calculation generic
body: <p>Im having some trouble building a function (or using some apply smartly) in R. I have a dataset like this: </p>
  
  <pre><code>df&lt;- data.frame( id &lt;-sample(1:10,100, replace = T),
  price &lt;-runif(20)*100,
  q = sample(1:100,100, replace = T))
  colnames(df)&lt;-c("id","price","quantity")
  </code></pre>
  
  <p>Now I need to calculate the average price for each individual ID. So I can do it by each different id like this: </p>
  
  <pre><code>sum(((df$p[df$id == "1" ])*(df$q[df$id == "1" ])/(sum(df$q[df$id == "1" ]))))  
  </code></pre>
  
  <p>But how do I make it go through all possible values of df$id and print it as a matrix/df, which also contains the ID alongside the sum? I have around 6000 different ID's and around 180000 obs. so it would be nice if it was also possible to do it fast? </p>
  
  <p>Breaking it down in a different way, assume this is my data: </p>
  
  <pre><code>id price quantity
  1   10    2
  1   20    1
  1   50    5
  2   5     5
  2   3     6 
  2   10    4
  </code></pre>
  
  <p>So here the solution for ID = 1 would be: <code>( 10 * 2 + 20*1 +50 * 5 ) / (2+1+5) = 36.25</code> This gives me the price pr. unit for all units with the ID = 1. </p>
  
  <p>Updated, using <code>set.seed(1234)</code> and this datageneration: </p>
  
  <pre><code>set.seed(1234)
  df&lt;- data.frame( id &lt;-sample(1:10,100, replace = T),
  price &lt;-runif(20)*100,
  q = sample(1:100,100, replace = T))
  colnames(df)&lt;-c("id","price","quantity")
  </code></pre>
  
  <p>The results should look like this : </p>
  
  <pre><code>id avg.price.per.unit
  1 33,71
  2 29,84
  3 44,53
  4 36,27
  5 69,63
  6 35,99
  7 45,26
  8 58,32
  9 33,36
  10 9,67
  </code></pre>
  
  <p>The rounding might be a little off.</p>