title: How can I subtract values within one column based on values in mutliple other columns?
body: <p>I have a dataframe like this:</p>
  <pre><code>dat &lt;- data.frame(c = c(rep(0, 3), rep(5, 3), rep(10, 3)),
                    id = c(rep(c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;), 3)),
                    measurement = c(1:8, 1))
  
  dat
  #    c id measurement
  # 1  0  A           1
  # 2  0  B           2
  # 3  0  C           3
  # 4  5  A           4
  # 5  5  B           5
  # 6  5  C           6
  # 7 10  A           7
  # 8 10  B           8
  # 9 10  C           1
  </code></pre>
  <p>I want to subtract the values in the column &quot;measurement&quot; where c is 0 from all other values in this column. This should happen separately based on the info given in the column &quot;id&quot;. E.g. the value where c is 0 and &quot;id&quot; is A should be subtracted from all values where c is &gt; 0 and &quot;id&quot; is A. The value where c is 0 and &quot;id&quot; is B should be subtracted from all values where c is &gt; 0 and &quot;id&quot; is B and so on.</p>
  <p>If the difference would be negative the result should be 0.</p>
  <p>The result should look like this:</p>
  <pre><code>result &lt;- data.frame(c = c(rep(0, 3), rep(5, 3), rep(10, 3)),
                   id = c(rep(c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;), 3)),
                   measurement = c(1:8, 1),
                   difference = c(0,0,0,3,3,3,6,6,0))
  
  result
  #    c id measurement difference
  # 1  0  A           1          0
  # 2  0  B           2          0
  # 3  0  C           3          0
  # 4  5  A           4          3
  # 5  5  B           5          3
  # 6  5  C           6          3
  # 7 10  A           7          6
  # 8 10  B           8          6
  # 9 10  C           1          0
  </code></pre>
  <p>I used dplyr to select the values of &quot;measurement&quot; based on the info from the other columns, but unfortunately I don't know how to do the calculations. So any suggestions are welcome!</p>