Skip to content

Instantly share code, notes, and snippets.

@nutterb
Created November 21, 2017 21:35
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 nutterb/f0c09e433ffe419d169dee7a25f58f72 to your computer and use it in GitHub Desktop.
Save nutterb/f0c09e433ffe419d169dee7a25f58f72 to your computer and use it in GitHub Desktop.
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")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment