Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(ggplot2)
- library(data.table)
- data("diamonds", package = "ggplot2")
- setDT(diamonds)
- arrange_dt <- function(DT, ...){
- setorderv(DT, as.character(as.list(substitute(list(...)))[-1L]))
- }
- arrange_dt(diamonds, carat)
- select_dt <- function(DT, ...){
- cols <- deparse(substitute(list(...)))
- cols <- sub("list\\(", ".(", cols)
- DT[j = eval(parse(text = cols))]
- }
- select_dt(diamonds, carat, cut, color, price)
- distinct_dt <- function(DT, ..., keep_all = FALSE){
- uniqueCols <- as.character(as.list(substitute(list(...)))[-1L])
- if (keep_all){
- unique(DT, by = uniqueCols)
- } else {
- select_dt(unique(DT, by = uniqueCols), ...)
- }
- }
- distinct_dt(diamonds, cut, color)
- distinct_dt(diamonds, cut, color, keep_all = TRUE)
- filter_dt <- function(DT, filters){
- z <- substitute(filters)
- DT[eval(z)]
- }
- filter_dt(diamonds, depth > 60)
- group_by_dt <- function(DT, ...){
- setattr(DT, "groups", as.character(as.list(substitute(list(...)))[-1L]))
- }
- group_by_dt(diamonds, cut, color)
- group <- function(DT){
- attr(DT, "groups")
- }
- group(diamonds)
- ungroup <- function(DT){
- setattr(DT, "groups", NULL)
- }
- ungroup(diamonds) %>>% group
- mutate_dt <- function(DT, ...){
- objects <- substitute(list(...))
- namesVar <- names(as.list(objects)[-1L])
- grps <- group(DT)
- if (is.null(grps)) {
- DT[j = `:=`(eval(namesVar), eval(objects))]
- } else {
- DT[j = `:=`(eval(namesVar), eval(objects)), by = grps]
- }
- }
- mutate_dt(ungroup(diamonds), V5 = depth - table, V6 = depth + table)
- mutate_dt(group_by_dt(diamonds, cut, color), V3 = mean(carat), V4 = max(price))
- summarise_dt <- function(DT, ...){
- objects <- deparse(substitute(list(...)))
- objects <- sub("list\\(", ".(", objects)
- grps <- group(DT)
- if (is.null(grps)) {
- DT[j = eval(parse(text = objects))]
- } else {
- DT[j = eval(parse(text = objects)), by = grps]
- }
- }
- summarise_dt(ungroup(diamonds), V3 = mean(carat), V4 = max(price))
- summarise_dt(group_by_dt(diamonds, cut, color), V3 = mean(carat), V4 = max(price))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement