adding a sub total in a column

Hi everyone.

I have a table which looks like the 1st 3 columns below. I wanted to add two more columns.
The fourth column is the total for each age_group and the last the proportion (2 dp) (3rd column/4th column).
Not sure how do do it.

code age_group n total proportion
0 0-5 12 42 0.29
1 0-5 15 42 0.36
2 0-5 10 42 0.24
3 0-5 5 42 0.12
0 6-10 7 61 0.11
1 6-10 21 61 0.34
2 6-10 15 61 0.25
3 6-10 18 61 0.30
0 11-15 20 57 0.35
1 11-15 25 57 0.44
2 11-15 10 57 0.18
3 11-15 2 57 0.04

Thanks.


library(tidyverse)
(madeupdf <- data.frame(c=rep(0:3,2),
                       a = sort(rep(letters[1:2],4)),
                       n = 1:8 *10))

(total_df <- group_by(madeupdf,
                     a) %>% summarise(
                       total=sum(n)
                     ))

(result_df <- left_join(madeupdf,
                        total_df) %>% 
                  mutate(prop = round(n/total,2)))

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.