Created
March 9, 2013 11:25
-
-
Save mrdwab/5123896 to your computer and use it in GitHub Desktop.
Version of `aggregate` where the function name is appended to the aggregated variable's name.
This file contains 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
myAgg <- function (formula, data, FUN, ..., subset, na.action = na.omit) | |
{ | |
if (missing(formula) || !inherits(formula, "formula")) | |
stop("'formula' missing or incorrect") | |
if (length(formula) != 3L) | |
stop("'formula' must have both left and right hand sides") | |
m <- match.call(expand.dots = FALSE) | |
if (is.matrix(eval(m$data, parent.frame()))) | |
m$data <- as.data.frame(data) | |
m$... <- m$FUN <- NULL | |
m[[1L]] <- as.name("model.frame") | |
if (formula[[2L]] == ".") { | |
rhs <- unlist(strsplit(deparse(formula[[3L]]), " *[:+] *")) | |
lhs <- sprintf("cbind(%s)", paste(setdiff(names(data), | |
rhs), collapse = ",")) | |
lhs | |
m[[2L]][[2L]] <- parse(text = lhs)[[1L]] | |
} | |
mf <- eval(m, parent.frame()) | |
if (is.matrix(mf[[1L]])) { | |
lhs <- as.data.frame(mf[[1L]]) | |
names(lhs) <- as.character(m[[2L]][[2L]])[-1L] | |
myOut <- aggregate.data.frame(lhs, mf[-1L], FUN = FUN, ...) | |
colnames(myOut) <- c(names(mf[-1L]), | |
paste(names(lhs), deparse(substitute(FUN)), sep = ".")) | |
} | |
else { | |
myOut <- aggregate.data.frame(mf[1L], mf[-1L], FUN = FUN, ...) | |
colnames(myOut) <- c(names(mf[-1L]), | |
paste(strsplit(gsub("cbind\\(|\\)|\\s", "", | |
names(mf[1L])), ",")[[1]], | |
deparse(substitute(FUN)), sep = ".")) | |
} | |
myOut | |
} | |
### Examples ### | |
# names(myAgg(weight ~ feed, data = chickwts, mean)) | |
# names(myAgg(breaks ~ wool + tension, data = warpbreaks, sum)) | |
# names(myAgg(weight ~ feed, data = chickwts, FUN = function(x) mean(x^2))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment