R/percTable.R

Defines functions percTable

Documented in percTable

#' Generate relative percentage table
#'
#' Creates a table of relative percentages for a given variable
#' @param .table Data table
#' @param .var Variable of interest
#' @param .names List of column name headers, usually used with prepLabels
#' @param .admbounds String specifying administrative codes
#' @return List giving counts and relative percentages
#' @export
#' @examples
#' percTable(data[['building']], 'dm_grade', c('ward','1','2','3','4','5'), 'ward')

percTable <- function(.table, .var, .names, .admbounds) {
  t <- .table %>% group_by_(.admbounds,.var) %>% count_(.var)
  groups <- dcast(t, t[[1]] ~ t[[2]], value.var = "n")
  groups[is.na(groups)] <- 0
  groups.p <- cbind(groups[1], prop.table(as.matrix(groups[-1]), margin = 1)*100)
  colnames(groups) <- .names
  colnames(groups.p) <- .names
  return(list(as.tibble(groups),as.tibble(groups.p)))
}
bradleyswilson/hrrp documentation built on May 28, 2019, 7:13 p.m.