title: Conditional calculation in R based on Row values and categories
body: <p>I have this dataframe:</p>
  
  <pre><code>df&lt;-data.frame(a=c("a1","a2","a3","a4","b1","b2","b3","b4","a1","a2","a3","a4","b1","b2","b3","b4"), b=c("x1","x2","x3","total","x1","x2","x3","total", "x1","x2","x3","total","x1","x2","x3","total"), reg=c("A","A","A","A","A","A","A","A","B", "B","B","B","B","B","B","B"), c=c(1:16))
  </code></pre>
  
  <p>which looks like:</p>
  
  <pre><code>    a     b reg  c
  1  a1    x1   A  1
  2  a2    x2   A  2
  3  a3    x3   A  3
  4  a4 total   A  4
  5  b1    x1   A  5
  6  b2    x2   A  6
  7  b3    x3   A  7
  8  b4 total   A  8
  9  a1    x1   B  9
  10 a2    x2   B 10
  11 a3    x3   B 11
  12 a4 total   B 12
  13 b1    x1   B 13
  14 b2    x2   B 14
  15 b3    x3   B 15
  16 b4 total   B 16
  </code></pre>
  
  <p>columns 'a', 'b' and 'reg' are categorical variables.  What I want to do is to create a new column which divides x(i), where i=1,2,3 with 'total' (x(i)/total) for each category in <code>reg' and in</code>a' columns. </p>
  
  <p>Can someone help me with this ?  </p>