# Proportion Calculation in r

I am confused to calculate the proprtion of certain value using mutate , however it gives a value of 1. how I can fix it?

``````x<- c(5,10,30,40,45,35)
y<- c("xrt","stu","brs","stu","ftc","xrt")
z<- c("bl","bl","xl","xl","dl","dl")
df<- data.frame(x,y,z)
library(tidyverse)
og<- df%>%group_by(y,z)%>%summarise(x=sum(x))
og<- og%>%mutate(pr = x/(sum(x)))

``````

y z x pr

1 brs xl 30 1
2 ftc dl 45 1
3 stu bl 10 0.2
4 stu xl 40 0.8
5 xrt bl 5 0.125
6 xrt dl 35 0.875

This is calculating the proportion within a unique value of y and r (don't see an r anywhere so I assume this was meant to be z). Since there are no duplicate pairs of y and z, these are all 100%. Did you perhaps just want to group within z?

I have edited, group by y and z , the sum of the proportion should be 1

Your data is still grouped. This will give you the proportions inside your `og` data.frame:

``````og <- df %>%
group_by(y,z) %>%
summarise(x = sum(x)) %>%
ungroup()

og %>%
mutate(pr = x/sum(x))
``````

Thank you , this is the solution

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.