Last active
September 16, 2017 10:39
-
-
Save QuentinRoy/06f607adb503d11ec6862f91af164ac1 to your computer and use it in GitHub Desktop.
A rewrite of ddply's summarize that 'flattens' named columns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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