Forked from dieulinh110/gist:0b5b17f10b2807c648b482682449b3fc
Last active
March 9, 2018 17:54
-
-
Save BroVic/3502366f7855cd0c660320beb8cd4e5f to your computer and use it in GitHub Desktop.
Calculating the sum of rows in each column group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## LOAD PACKAGE | |
library(dplyr) | |
## INPUT | |
input <- data.frame(president = c("A1", "A1", "A1", "A1", "A1", "A1", "A1"), | |
vice_president = c("B", "B", "B", "B", "C", "C", "C"), | |
manager = c("D", "D", "E", "E", "F", "G", "H"), | |
staff = c("I", "J", "K", "L", "M", "N", "O"), | |
qty_1 = c(1:7), | |
qty_2 = c(2:8), | |
qty_3 = c(1:7), | |
stringsAsFactors = FALSE) | |
## PROCESSING | |
### Group manager | |
out_manager <- input %>% | |
group_by(president, vice_president, manager) %>% | |
summarise_at(vars(qty_1, qty_2, qty_3), funs(sum(., na.rm = TRUE))) %>% | |
mutate(manager = paste(manager, "Total", sep = " ")) %>% | |
bind_rows(input) %>% | |
arrange(president, vice_president, manager) | |
### Group vice-president | |
out_vice_president <- input %>% | |
group_by(president, vice_president) %>% | |
summarise_at(vars(qty_1, qty_2, qty_3), funs(sum(., na.rm = TRUE))) %>% | |
mutate(vice_president = paste(vice_president, "Total")) %>% | |
bind_rows(out_manager) %>% | |
arrange(president, vice_president) | |
### Group president | |
out_president <- input %>% | |
group_by(president) %>% | |
summarise_at(vars(qty_1, qty_2, qty_3), funs(sum(., na.rm = TRUE))) %>% | |
mutate(president = paste(president, "Total")) %>% | |
bind_rows(out_vice_president) %>% | |
arrange(president) %>% | |
mutate_all(funs(replace(., is.na(.), ""))) %>% | |
mutate_at(vars(president, vice_president), funs(ifelse(grepl("Total", manager), "", .))) %>% | |
mutate(president = ifelse(grepl("Total", vice_president), "", president)) | |
## OUTPUT | |
output <- out_president %>% | |
select(president, vice_president, manager, | |
staff, qty_1, qty_2, qty_3) | |
write.csv(output, "output.csv") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment