Calculating row percentages using Dplyr [duplicate]

Does this work:

>library(dplyr)
> df %>% group_by(ID, Month, Year) %>% mutate(Percent = Value/sum(Value)) %>% 
group_by(Month, Year,DOW) %>% summarise(Avg = mean(Percent)) %>% as.data.frame()
`summarise()` regrouping output by 'Month', 'Year' (override with `.groups` argument)
  Month Year DOW       Avg
1   Feb 2019 Fri 0.4027778
2   Feb 2019 Sat 0.5972222
3   Jan 2019 Fri 0.4819915
4   Jan 2019 Sat 0.5180085
> 

Data used:

structure(list(ID = c(1, 1, 1, 1, 2, 2, 2, 2), Month = c("Jan", 
"Jan", "Feb", "Feb", "Jan", "Jan", "Feb", "Feb"), Year = c(2019, 
2019, 2019, 2019, 2019, 2019, 2019, 2019), DOW = c("Fri", "Sat", 
"Fri", "Sat", "Fri", "Sat", "Fri", "Sat"), Value = c(20, 39, 
30, 24, 20, 12, 1, 3)), class = c("spec_tbl_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -8L), spec = structure(list(
    cols = list(ID = structure(list(), class = c("collector_double", 
    "collector")), Month = structure(list(), class = c("collector_character", 
    "collector")), Year = structure(list(), class = c("collector_double", 
    "collector")), DOW = structure(list(), class = c("collector_character", 
    "collector")), Value = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top