-3

I have the below example data frame DF:

Group id    absolute
A     123   600
A     1234  300
A     12345 100
B     321   300
B     4321  300
B     5321  400

and want to converted to calculate the relative share of the ids within the group they belong to

Group id    share
A     123   60%
A     1234  30%
A     12345 10%
B     321   30%
B     4321  30%
B     5321  40%

I've tried

DF%>%group_by(Group,id)%>%summarise(share=absolute/colSums(absolute))
nba2020
  • 618
  • 1
  • 8
  • 22

1 Answers1

1

dplyr will help here. You just need to divide absolute with total of absolute of particular group.

x %>%
  group_by(Group_id) %>%
  mutate(new = (absolute/sum(absolute)) * 100)


Group_id    id  absolute    new
<fct>   <dbl>   <dbl>   <dbl>
A   123 600 60
A   1234    300 30
A   12345   100 10
B   321 300 30
B   4321    300 30
B   5321    400 40
Bhavesh Ghodasara
  • 1,981
  • 2
  • 15
  • 29