Get difference of two categories within a group and repeat for each variable, R

15 Views Asked by At

My data looks a little something like this, with Rate 1-81.


Name     Month  Rate1     Rate2  Rate3...... Rate81
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32

What I want to do is get the difference of 1&2, 2&3, 1&3 for each person. I want to do this for each 'rate'. I can do this manually but I have 81 variables and I have not figured out how to make this code succinct and into one dataframe.

The main this is how do I duplicate this across variables (i.e. Rate 1-81)

This is what I have done for one combination and one variable.

data1 %>%
  group_by(Name) %>%
  summarise(diff = Rate1[match('1', Month)] - Rate1[match('2', Month)])

I've also tried aggregate but I don't know how to turn the above into a function that I could input instead of 'mean'

aggregate(data1[, 2:82], list(data1$Name), mean)

in the end I want to get


Difference Rate1     Rate2  Rate3...... Rate81
Aira1-2  
Aira1-3
....     
0

There are 0 best solutions below