在 R 中使用 data.table 自定义函数,分组依据不识别组参数



我只是想创建一个按组求和的函数。但是,似乎该函数从未找到'my_group'参数。解决方案需要在函数内部。的数据。Table '和'tidyverse'选项可以在函数外工作。

我在这里错过了什么?

data=data.table(
group= c('a','b','b','c','c','c'),
value=1:6
)
sum_value_by_group<-function(dt, val, my_group) {
dt[,group_value:= sum(val), by = my_group]
return(dt)
}
sum_value_by_group(data, value, group)

得到这个错误:eval(bysub, x, parent.frame())出错:object 'group' not found

一种选择是使用get并将列名作为字符串传递。

library(data.table)
sum_value_by_group<-function(dt, val, my_group) {
dt[, .(group_value = sum(get(val))), by = list(group = get(my_group))]
}
sum_value_by_group(data, 'value', 'group')
#   group group_value
#1:     a           1
#2:     b           5
#3:     c          15

最新更新