Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- quick_summary <- function(df, vars, group = NULL){
- group_is_null <- is.null(group)
- coll <- checkmate::makeAssertCollection()
- checkmate::assert_data_frame(x = df,
- add = coll)
- checkmate::assert_character(x = vars,
- add = coll)
- checkmate::assert_character(x = group,
- null.ok = TRUE,
- add = coll)
- checkmate::assert_subset(x = vars,
- choices = names(df),
- add = coll)
- if (!group_is_null){
- checkmate::assert_subset(x = group,
- choices = names(df),
- add = coll)
- }
- if (any(vars %in% group)){
- in_both <- vars[vars %in% group]
- coll$push(paste0("The following variables names are in both 'vars' and 'group': ",
- paste0(in_both, collapse = ", ")))
- }
- checkmate::reportAssertions(coll)
- df <- df[c(vars, group)]
- checkmate::assert_data_frame(x = df[vars],
- types = "numeric",
- .var.name = "vars",
- add = coll)
- checkmate::reportAssertions(coll)
- if (!group_is_null){
- group_order <-
- lapply(df[group],
- function(x) if (is.factor(x)) levels(x) else unique(x))
- group_order <- stats::setNames(group_order, group)
- }
- ncount <- function(x, na.rm = TRUE) sum(!is.na(x))
- df <- tidyr::gather(data = df,
- key = !!"variable",
- value = !!"value",
- dplyr::one_of(vars))
- df <- dplyr::group_by_at(.tbl = df,
- .vars = c("variable", group))
- df <- dplyr::summarise_at(.tbl = df,
- .vars = "value",
- .fun = dplyr::funs(
- n = ncount,
- mean = mean,
- sd = sd,
- min = min,
- median = median,
- max = max
- ),
- na.rm = TRUE)
- df$variable <- factor(df$variable, levels = vars)
- if (!group_is_null){
- df[group] <- mapply(factor,
- x = df[group],
- levels = group_order)
- }
- dplyr::arrange_at(.tbl = df, "variable")
- }
Add Comment
Please, Sign In to add comment