Advertisement
celestialgod

dplyr form for data.table

Mar 9th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 2.02 KB | None | 0 0
  1. library(ggplot2)
  2. library(data.table)
  3.  
  4. data("diamonds", package = "ggplot2")
  5. setDT(diamonds)
  6.  
  7. arrange_dt <- function(DT, ...){
  8.   setorderv(DT, as.character(as.list(substitute(list(...)))[-1L]))
  9. }
  10. arrange_dt(diamonds, carat)
  11.  
  12. select_dt <- function(DT, ...){
  13.   cols <- deparse(substitute(list(...)))
  14.   cols <- sub("list\\(", ".(", cols)
  15.   DT[j = eval(parse(text = cols))]
  16. }
  17. select_dt(diamonds, carat, cut, color, price)
  18.  
  19. distinct_dt <- function(DT, ..., keep_all = FALSE){
  20.   uniqueCols <- as.character(as.list(substitute(list(...)))[-1L])
  21.   if (keep_all){
  22.     unique(DT, by = uniqueCols)
  23.   } else {
  24.     select_dt(unique(DT, by = uniqueCols), ...)
  25.   }
  26. }
  27. distinct_dt(diamonds, cut, color)
  28. distinct_dt(diamonds, cut, color, keep_all = TRUE)
  29.  
  30. filter_dt <- function(DT, filters){
  31.   z <- substitute(filters)
  32.   DT[eval(z)]
  33. }
  34. filter_dt(diamonds, depth > 60)
  35.  
  36. group_by_dt <- function(DT, ...){
  37.   setattr(DT, "groups", as.character(as.list(substitute(list(...)))[-1L]))
  38. }
  39. group_by_dt(diamonds, cut, color)
  40.  
  41. group <- function(DT){
  42.   attr(DT, "groups")
  43. }
  44. group(diamonds)
  45.  
  46. ungroup <- function(DT){
  47.   setattr(DT, "groups", NULL)
  48. }
  49. ungroup(diamonds) %>>% group
  50.  
  51. mutate_dt <- function(DT, ...){
  52.   objects <- substitute(list(...))
  53.   namesVar <- names(as.list(objects)[-1L])
  54.   grps <- group(DT)
  55.   if (is.null(grps)) {
  56.     DT[j = `:=`(eval(namesVar), eval(objects))]
  57.   } else {
  58.     DT[j = `:=`(eval(namesVar), eval(objects)), by = grps]
  59.   }
  60. }
  61. mutate_dt(ungroup(diamonds), V5 = depth - table, V6 = depth + table)
  62. mutate_dt(group_by_dt(diamonds, cut, color), V3 = mean(carat), V4 = max(price))
  63.  
  64. summarise_dt <- function(DT, ...){
  65.   objects <- deparse(substitute(list(...)))
  66.   objects <- sub("list\\(", ".(", objects)
  67.   grps <- group(DT)
  68.   if (is.null(grps)) {
  69.     DT[j = eval(parse(text = objects))]
  70.   } else {
  71.     DT[j = eval(parse(text = objects)), by = grps]
  72.   }
  73. }
  74. summarise_dt(ungroup(diamonds), V3 = mean(carat), V4 = max(price))
  75. summarise_dt(group_by_dt(diamonds, cut, color), V3 = mean(carat), V4 = max(price))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement