I have trying to calculate percentage of a row by group but i don't seem to get it.
Data
df = data.frame(ID = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 4L),
ID_name = c("AA", "AA", "BB", "BB", "CC", "CC", "DD", "DD", "DD"),
Volume = c(10L, 20L, 30L, 50L, 50L, 40L, 20L, 30L, 10L))
I want it to create a new column (Percentage) which will calculate Proportion of volume by ID
Ideal data will look like this (for all IDs but right now I am only showing for ID=1)
ID ID_Name Volume Percentage
1 AA 10 0.33
1 AA 20 0.67
I tried this code but it doesn't seem to work
df %>%
group_by(ID) %>%
mutate(PercVol = Volume/sum(Volume))
Output of the code:
ID ID_name Volume PercVol
(int) (fctr) (int) (dbl)
1 1 AA 10 0.03846154
2 1 AA 20 0.07692308
3 2 BB 30 0.11538462
4 2 BB 50 0.19230769
5 3 CC 50 0.19230769
6 3 CC 40 0.15384615
7 4 DD 20 0.07692308
8 4 DD 30 0.11538462
9 4 DD 10 0.03846154