假设我有以下代码:
library(data.table)
cars1 = setDT(copy(cars))
cars2 = setDT(copy(cars))
car_list = list(cars1, cars2)
class(car_list) <- "dd"
`[.dd` <- function(x,...) {
code = rlang::enquos(...)
cars1 = x[[1]]
rlang::eval_tidy(quo(cars1[!!!code]))
}
car_list[,.N, by = speed]
我希望通过定义[.dd
函数来对cars1
和cars2
执行任意操作,无论我在...
中放入什么,都会使用[
data.table句法在cars1
和cars2
上执行。
例如:car_list[,.N, by = speed]
应该执行以下操作:
cars1[,.N, by = speed]
cars2[,.N, by = speed]
我也想要
car_list[,speed*2]
待完成
cars1[,speed*2]
cars2[,speed*2]
基本上,在[.dd
中的...
需要接受任意代码。
我需要捕获...
,所以我尝试使用code = rlang::enquos(...)
,然后rlang::eval_tidy(quo(cars1[!!!code]))
不起作用并出现错误。
[.data.table
(cars1, ~, ~.N, by = ~speed) : 缺少参数“i”,没有默认值。
rlang :: enexprs
替换enquos
,并删除eval_tidy
内部的quo
调用,它不是必需的。 - Alexis