|
| 1 | +############################## GroupedData ######################################## |
| 2 | + |
| 3 | +setClass("GroupedData", |
| 4 | + slots = list(env = "environment", |
| 5 | + sgd = "jobj")) |
| 6 | + |
| 7 | +setMethod("initialize", "GroupedData", function(.Object, sgd) { |
| 8 | + .Object@env <- new.env() |
| 9 | + .Object@sgd <- sgd |
| 10 | + .Object |
| 11 | +}) |
| 12 | + |
| 13 | +groupedData <- function(sgd) { |
| 14 | + new("GroupedData", sgd) |
| 15 | +} |
| 16 | + |
| 17 | +setMethod("count", |
| 18 | + signature(x = "GroupedData"), |
| 19 | + function(x) { |
| 20 | + dataFrame(callJMethod(x@sgd, "count")) |
| 21 | + }) |
| 22 | + |
| 23 | +#' Agg |
| 24 | +#' |
| 25 | +#' Aggregates on the entire DataFrame without groups. |
| 26 | +#' |
| 27 | +#' df2 <- agg(df, <column> = <aggFunction>) |
| 28 | +#' df2 <- agg(df, newColName = aggFunction(column)) |
| 29 | +#' @examples |
| 30 | +#' \dontrun{ |
| 31 | +#' df2 <- agg(df, age = "sum") # new column name will be created as 'SUM(age#0)' |
| 32 | +#' df2 <- agg(df, ageSum = sum(df$age)) # Creates a new column named ageSum |
| 33 | +#' } |
| 34 | +setGeneric("agg", function (x, ...) { standardGeneric("agg") }) |
| 35 | + |
| 36 | +setMethod("agg", |
| 37 | + signature(x = "GroupedData"), |
| 38 | + function(x, ...) { |
| 39 | + cols = list(...) |
| 40 | + stopifnot(length(cols) > 0) |
| 41 | + if (is.character(cols[[1]])) { |
| 42 | + cols <- varargsToEnv(...) |
| 43 | + sdf <- callJMethod(x@sgd, "agg", cols) |
| 44 | + } else if (class(cols[[1]]) == "Column") { |
| 45 | + ns <- names(cols) |
| 46 | + if (!is.null(ns)) { |
| 47 | + for (n in ns) { |
| 48 | + if (n != "") { |
| 49 | + cols[[n]] = alias(cols[[n]], n) |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + jcols <- lapply(cols, function(c) { c@jc }) |
| 54 | + sdf <- callJMethod(x@sgd, "agg", jcols[[1]], listToSeq(jcols[-1])) |
| 55 | + } else { |
| 56 | + stop("agg can only support Column or character") |
| 57 | + } |
| 58 | + dataFrame(sdf) |
| 59 | + }) |
| 60 | + |
| 61 | +#' sum/mean/avg/min/max |
| 62 | + |
| 63 | +methods <- c("sum", "mean", "avg", "min", "max") |
| 64 | + |
| 65 | +createMethod <- function(name) { |
| 66 | + setMethod(name, |
| 67 | + signature(x = "GroupedData"), |
| 68 | + function(x, ...) { |
| 69 | + sdf <- callJMethod(x@sgd, name, toSeq(...)) |
| 70 | + dataFrame(sdf) |
| 71 | + }) |
| 72 | +} |
| 73 | + |
| 74 | +createMethods <- function() { |
| 75 | + for (name in methods) { |
| 76 | + createMethod(name) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +createMethods() |
| 81 | + |
0 commit comments