Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BroVic/3502366f7855cd0c660320beb8cd4e5f to your computer and use it in GitHub Desktop.
Save BroVic/3502366f7855cd0c660320beb8cd4e5f to your computer and use it in GitHub Desktop.
Calculating the sum of rows in each column group
## 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