1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| library(dplyr) library(pipeR) library(ggplot2) library(data.table)
data("diamonds", package = "ggplot2")
df_group_fn <- function(df, meanCol, col_1, col_2){ df %>>% group_by_(.dots = c(col_1, col_2)) %>>% summarise_(.dots = c(n = "n()", mean = paste0("mean(", meanCol, ")"))) %>>% {ggplot(., aes(mean,n)) + geom_point()} } df_group_fn(diamonds, "price", "cut", "color")
dt_group_fn <- function(dt, meanCol, col_1, col_2){ dt[ , .(n = .N, mean = eval(parse(text = paste0("mean(", meanCol, ")")))), by = c(col_1, col_2)] %>>% {ggplot(., aes(mean,n)) + geom_point()} } dt_group_fn(data.table(diamonds), "price", "cut", "color")
library(wrapr) df_group_fn2 <- function(df, meanCol, col_1, col_2){ let(list(y = meanCol, c1 = col_1, c2 = col_2), { df %>>% group_by(c1, c2) %>>% summarise(n = n(), mean = mean(y)) }) %>>% {ggplot(., aes(mean,n)) + geom_point()} } df_group_fn2(diamonds, "price", "cut", "color")
dt_group_fn2 <- function(dt, meanCol, col_1, col_2){ let(list(y = meanCol, c1 = col_1, c2 = col_2), { dt[ , .(n = .N, mean = mean(y)), by = .(c1, c2)] }) %>>% {ggplot(., aes(mean,n)) + geom_point()} } dt_group_fn2(data.table(diamonds), "price", "cut", "color")
df_group_fn3 <- function(df, meanCol, groupByCols){ let(list(y = meanCol), { df %>>% group_by_(.dots = groupByCols) %>>% summarise(n = n(), mean = mean(y)) }) %>>% {ggplot(., aes(mean,n)) + geom_point()} } df_group_fn3(diamonds, "price", c("cut", "color"))
dt_group_fn3 <- function(dt, meanCol, groupByCols){ let(list(y = meanCol), { dt[ , .(n = .N, mean = mean(y)), by = groupByCols] }) %>>% {ggplot(., aes(mean,n)) + geom_point()} } dt_group_fn3(data.table(diamonds), "price", c("cut", "color"))
|