0

I have generated data as follows:

Group  Detail  Value  Count  Count_Avg
A      P       1.25   2      0.63  
A      K       0.5    1      0.50  
A      Y       0.25   1      0.25
B      D       0.75   2      0.38
B      G       33.5   18     1.86
B      Q       17.5   18     0.97

The full set of data for the code below has for example: 2 instances of Detail "P" in Group "A" with a sum of a variable called Time (not shown, Time for P1 = 0.75, Time for P2 = 0.50) of 1.25 for the Value and an average of 0.63 for the Count_Avg. There are 18 instances of Detail "G" in Group "B" with a sum of 33.5 for the Value and an average of 1.86 for the Count_Avg, and so on.

This is the code that I use to generate the above table.

data %>%
group_by(Group,
         Detail) %>%
summarise(Value = sum(Time),
          n = n(),
          Count_Avg = Value/n)

I want to add another column that is the percentage of Group for each Detail. As an example:

Total Value for all Details in Group "A" = 1.25 + 0.5 + 0.25 = 2.0, and the percentage of Detail "P" in Group "A"= 1.25/2.0 = 0.625. The resultant table would look like this:

Group  Detail  Value  Count  Count_Avg  Detail_Pcnt
A      P       1.25   2      0.63       0.625
A      K       0.5    1      0.50       0.250
A      Y       0.25   1      0.25       0.125
B      D       0.75   1      0.75       0.014
B      G       33.5   18     1.86       0.647
B      Q       17.5   18     0.97       0.338

Thanks for you assistance.

Austin Overman
  • 163
  • 2
  • 9
  • Your code doesn't at all link up with your data – Axeman Oct 12 '16 at 22:04
  • I already fixed your formatting, I'm going to roll back your changes back, OK? – Axeman Oct 12 '16 at 22:06
  • My guess is that you want to add `%>% mutate(perc = Value / sum(Value))` to the end of your pipe chain. – Axeman Oct 12 '16 at 22:10
  • 1
    Many thanks Axman, both fixing the formatting (which I also did), but more importantly the answer; that worked perfectly. It is always the obvious that is the most difficult to see. – Austin Overman Oct 12 '16 at 23:10
  • @cuttlefish44, `mutate` by itself already respects grouping in calculating the `sum`, and should be faster than using `do`. – Axeman Oct 13 '16 at 09:34

0 Answers0