Skip to content

Instantly share code, notes, and snippets.

@QuentinRoy
Last active September 16, 2017 10:39
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 QuentinRoy/06f607adb503d11ec6862f91af164ac1 to your computer and use it in GitHub Desktop.
Save QuentinRoy/06f607adb503d11ec6862f91af164ac1 to your computer and use it in GitHub Desktop.
A rewrite of ddply's summarize that 'flattens' named columns
# Fork of ddply's summarize that 'flattens' named columns
flat.summarize <- function (data, ...) {
stopifnot(is.data.frame(data) || is.list(data) || is.environment(data))
cols <- as.list(substitute(list(...))[-1])
if (is.null(names(cols))) {
missing_names <- rep(TRUE, length(cols))
}
else {
missing_names <- names(cols) == ""
}
if (any(missing_names)) {
names <- unname(unlist(lapply(match.call(expand.dots = FALSE)$...,
deparse)))
names(cols)[missing_names] <- names[missing_names]
}
data <- as.list(data)
for (col in names(cols)) {
res <- eval(cols[[col]], data, parent.frame())
# addition from original summarize so that it accepts functions
# returning more than one named columns
if(length(res) > 1) {
for(name in names(res)) {
col.name <- paste(col, name, sep='.')
col.res <- res[[name]]
# add in cols for quickdf
cols[[col.name]] <- col.res
data[[col.name]] <- col.res
}
# rm the base col
cols <- cols[names(cols)!=col]
} else {
data[[col]] <- eval(cols[[col]], data, parent.frame())
}
}
quickdf(data[names(cols)])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment