我正在研究一个data.table
在内部使用的包。在这个包中,我有一个函数,它计算 a by 组count_by
中特定变量的不同 ID 的数量。data.table
在一些帮助下(R data.table: How to pass "everything possible" to by in a function?)我得到了这个按预期工作:
library(data.table)
#> Warning: package 'data.table' was built under R version 3.6.2
# create example data
sample_dt <- data.table(
id = sort(rep(LETTERS[1:3], 3)),
year = rep(2018L:2020L),
x = runif(9)
)
sample_dt[id == "B" & year < 2020, x := NA_real_]
# define inner function
count_by <- function(DT, id_var, val_var, by = NULL) {
id_var <- as.character(substitute(id_var))
val_var <- as.character(substitute(val_var))
eval(substitute(
DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
))
}
# test inner function -> works as expected
(reference <- count_by(sample_dt, id_var = id, val_var = x, by = year))
#> year distinct_ids
#> 1: 2018 2
#> 2: 2019 2
#> 3: 2020 3
identical(count_by(sample_dt, "id", x, year) , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", year) , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, "year") , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", x, c("year")) , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", "year") , reference)
#> [1] TRUE
identical(count_by(sample_dt, "id", "x", c("year")), reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", year) , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", "year") , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, "x", c("year")) , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, "year") , reference)
#> [1] TRUE
identical(count_by(sample_dt, id, x, c("year")) , reference)
#> [1] TRUE
由reprex 包于 2020-02-20 创建(v0.3.0)
现在我想count_by()
在另一个函数中使用该函数(下面的最小示例):
# define wrapper function
wrapper <- function(data, id_var, val_var, by = NULL) {
data <- as.data.table(data)
count_by(data, id_var, val_var, by)
}
# test wrapper function
wrapper(sample_dt, id_var = id, val_var = x, by = year)
#> Error in .(distinct_ids = uniqueN(get("id_var"))): could not find function "."
由reprex 包于 2020-02-20 创建(v0.3.0)
调试count_by()
导致观察到,如果count_by()
从 调用wrapper()
,substitute(DT[...])
也可以替换DT
为data
:
Browse[2]> substitute(
+ DT[!is.na(get(val_var)), .(distinct_ids = uniqueN(get(id_var))), by = by]
+ )
data[!is.na(get("val_var")), .(distinct_ids = uniqueN(get("id_var"))),
by = by]
由于data
在它的功能环境中不可用,count_by()
因此会对其进行评估,utils::data
从而导致错误。这使问题变得清晰,但我想不出解决方案。
我需要替换整个DT[...]
表达式才能by
正常工作(请参阅R data.table: How to pass "everything possible" to by in a function?或将变量和名称传递给 data.table 函数)。但是我不能为了不被替换而替换整个表达式DT
。
解决这个困境的方法是什么?