Skip to content

Instantly share code, notes, and snippets.

@lionel-
Created June 25, 2019 10:54
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 lionel-/b1650305567962338b6441c72fe6eb18 to your computer and use it in GitHub Desktop.
Save lionel-/b1650305567962338b6441c72fe6eb18 to your computer and use it in GitHub Desktop.
Wrapping DT
# Simple DT wrapper
summarise <- function(data, j, by) {
data <- data.table::as.data.table(data)
data[
i = ,
j = eval(substitute(j)),
by = eval(substitute(by))
]
}
# It works in simple cases, though the columns don't have good default labels:
summarise(mtcars, mean(disp), cyl)
#> substitute V1
#> 1: 6 183.3143
#> 2: 4 105.1364
#> 3: 8 353.1000
# The main issue is that it can't be reused in packages:
local({
mysummary <- mean # Simulating package function
summarise(mtcars, mysummary(disp), cyl)
})
#> Error in mysummary(disp) : could not find function "mysummary"
# The wrapper can't be rewrapped easily:
summarise_cyl <- function(data, j) {
summarise(data, j, by = cyl)
}
summarise_cyl(mtcars, mean(disp))
#> Error in mean(disp) : object 'disp' not found
# Needs to use eval(), bquote(), and substitute()
summarise_cyl <- function(data, j) {
eval(bquote(summarise(data, .(substitute(j)), by = cyl)))
}
summarise_cyl(mtcars, mean(disp))
#> substitute V1
#> 1: 6 183.3143
#> 2: 4 105.1364
#> 3: 8 353.1000
# Can't be reused in package:
local({
x <- 10
summarise_cyl(mtcars, mean(disp) * x)
})
#> Error in `[.data.table`(data, i = , j = eval(substitute(j)), by = eval(substitute(by))) :
#> object 'x' not found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment