tidy evaluation in "grouped" data.table

I'm trying to use tidy evaluation with data.table while grouping. My question is quite related to Clarifying question - When is manual data mask needed in `rlang::eval_tidy`?. Maybe ildi.czeller has something to say about it?

Say I want to group by b and do mean.

library(data.table)
library(rlang)

DT <- data.table(a=1:10, b=c(rep(1,5), rep(2,5)))

##works
DT[,.(mean(a)), by =(b)]
##    b V1
## 1: 1  3
## 2: 2  8

And now I want to use this in a function where the user could write the function themselves, stored in user_func. Now eva_tidy ignores the grouping, I guess it has to do with the data mask. But is there a way to tell to eval tidy that user_func should be evaluated in the context of each group?

user_func <- quos(mean(a))

## ignores the grouping
eval_tidy(quo(DT[,.(!!!user_func), by =(b)]), DT)
eval_tidy(quo(DT[,.(!!!user_func), by =(b)]), as_data_mask(DT))
##    b V1
## 1: 1  5.5
## 2: 2  5.5

I can make it work using the expression, but this can break if the expression has inside a quosure.

##works
DT[,.(eval(quo_get_expr(user_func[[1]]))), by =(b)]
##    b V1
## 1: 1  3
## 2: 2  8

Any ideas?

I could be totally wrong, but I don't think rlang is designed to work with data.table, which has its own non-standard evaluation mechanisms. Here is an old link on SO,, so there may be more up-to-date solutions:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.