Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created March 9, 2013 11:25
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 mrdwab/5123896 to your computer and use it in GitHub Desktop.
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.
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