Created
April 4, 2016 10:45
-
-
Save benwhalley/2649c4ac74061594abb711ecd89f9c20 to your computer and use it in GitHub Desktop.
dcastMult.R
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
# http://stackoverflow.com/questions/21477040/reshape2-multiple-results-of-aggregation-function | |
dcastMult <- function(data, formula, value.var = "value", | |
funs = list("min" = min, "max" = max)) { | |
require(reshape2) | |
if (is.null(names(funs)) | any(names(funs) == "")) stop("funs must be named") | |
Form <- formula(formula) | |
LHS <- as.character(Form[[2]]) | |
if (length(LHS) > 1) LHS <- LHS[-1] | |
temp <- lapply(seq_along(funs), function(Z) { | |
T1 <- dcast(data, Form, value.var = value.var, | |
fun.aggregate=match.fun(funs[[Z]]), fill = 0) | |
Names <- !names(T1) %in% LHS | |
names(T1)[Names] <- paste(names(T1)[Names], names(funs)[[Z]], sep = "_") | |
T1 | |
}) | |
Reduce(function(x, y) merge(x, y), temp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment