title: Group-wise operation by factor in data frame
body: <p>Consider the following data frame</p>
  
  <pre><code> ## Example data frame
      z1&lt;-c("a", "b", "c", "c", "b", "a", "a", "b", "c") ##groups
      z2&lt;-c("x", "x", "x", "y", "y", "y", "z", "z", "z") ##experiments
      z3&lt;-c(2,4,8,15,9,3,1,2,3)                          ##results
      df&lt;-data.frame(group=z1, id=z2, res=z3)            ##z1, z2, and z3 to data frame
  </code></pre>
  
  <p>I'd like to automatically generate the column (<code>z4</code>), which is the fold change for the data in <code>z3</code>.</p>
  
  <p>The calculation I would like to perform is:</p>
  
  <blockquote>
    <p>a/a &amp; b/a &amp; c/a for id=x and c/a &amp; b/a &amp; c/a for id=y etc.</p>
  </blockquote>
  
  <p>and add the results in a new column of the data frame.</p>
  
  <p>i.e., </p>
  
  <pre><code>df$z4 &lt;- c(1,2,4,5,3,1,1,2,3) ## by hand
  </code></pre>
  
  <p>My line of thought was that I should break the problem down with something like:</p>
  
  <pre><code>###function to check whether group=a, returns TRUE/FALSE
  checkA&lt;-function(x){
    if(x=="a"){
      res=TRUE
    }else {
      res=FALSE
    }
  return(res)
  }
  
  ### checks whether a is in df$group
  df$check&lt;-lapply(df$group, checkA)
  </code></pre>
  
  <p>But it did not really help. I have the feeling that this can be done with built-in functions (one of the <code>apply</code>s or <code>ifelse</code>) but I cannot get my head around it.</p>