Triamus / play

play repo for experiments (mainly with git)
1 stars 0 forks source link

agg_to_barplot function #10

Open Triamus opened 7 years ago

Triamus commented 7 years ago

agg_to_barplot <- function(data, select_vars, group_vars, metric, agg_type = "sum", facet_var, dimension, fill_var = "flgdata", scale = 1){

# required libraries
base::lapply(c("ggplot2", "scales"), require, character.only = TRUE)

# build evaluation of aggregation function
e <- base::eval(parse(text=paste0("function(x) {", 
                                  agg_type, "(", "x, na.rm = T)}")))

# convert character vector to list of symbols
dots_group <- base::lapply(group_vars, as.name)

data %>%
  select_(.dots = select_vars) %>%
  group_by_(.dots = dots_group) %>%
  summarise_at(.cols = paste0(metric), .funs = funs(e)) %>%
  mutate_at(.cols = paste0(metric), .funs = function(x) x / scale) %>%
  ggplot2::ggplot(aes_string(x = dimension, y = metric, 
                             fill = fill_var)) +
  ggplot2::geom_bar(stat = "identity", position = "dodge") +
  ggplot2::facet_wrap(as.formula(paste("~", facet_var))) +
  # scale_y_continuous is not an exported object from namespace:scales
  scale_y_continuous(labels = comma) +
  ggplot2::labs(title = paste(metric, "by", dimension), 
                x = dimension, y = paste(metric, "(in mn) \n"))
}

agg_to_barplot( data = gcst_all, select_vars = c("repdtetrn", "flgdata", "rating", "rwab2epe"), group_vars = c("repdtetrn", "flgdata", "rating"), metric = "rwab2epe", dimension = "rating", fill_var = "flgdata", facet_var = "repdtetrn", agg_type = "sum", scale = 1000000)