Search code examples
rrowsubtraction

Substract one row from another with conditions


I have a table like this:

  treatment individual phase dist_mean  track
1   control          1   pre     13.33 569.99
2   control          1  post     10.95 624.65
3   control          2   pre      9.93 363.35
4   control          2  post     10.11 339.88
5   control          3   pre     12.00 676.42
6   control          3  post     12.80 939.15

In principle, two rows are always paired. I need to subtract dist_mean of the post-phase from the pre-phase of a sample. The easy way would be to subtract row 2 from 1 and so on. But given the possibility that this order is disturbed at any point, the whole calculation would go wrong. That's why I would like to have the calculation under the conditions, that the treatment and the individual of both phases match. Info: the treatment changes. It's not always control.


Solution

  • Use aggregate:

    aggregate(dist_mean ~ treatment + individual, df1, function(x) diff(rev(x)))
    #  treatment individual dist_mean
    #1   control          1      2.38
    #2   control          2     -0.18
    #3   control          3     -0.80
    

    Data

    df1 <- read.table(text = "
      treatment individual phase dist_mean  track
    1   control          1   pre     13.33 569.99
    2   control          1  post     10.95 624.65
    3   control          2   pre      9.93 363.35
    4   control          2  post     10.11 339.88
    5   control          3   pre     12.00 676.42
    6   control          3  post     12.80 939.15
    ", header = TRUE)