I want to write a function outer_fun(), which does some things and also calls another function inner_fun(). All arguments from outer_fun() are passed to inner_fun().
inner_fun() does some calculations on a data.table (which is an argument to both functions). Another argument to be passed through the function is by.
Here is a sketch of what I have:
library(data.table)
data("CO2")
setDT(CO2)
outer_fun <- function(DT, by) {
# some other stuff
by <- substitute(by)
inner_fun(DT, by)
}
inner_fun <- function(DT, by) {
DT[, .(mean = mean(uptake)),
by = list(Plant, by)]
}
outer_fun(CO2, by = Type)
This throws an error:
Error in `[.data.table`(DT, , .(mean = mean(uptake)), by = list(Plant, :
column or expression 2 of 'by' or 'keyby' is type language. Do not quote column names. Usage: DT[,sum(colC),by=list(colA,month(colB))]
As far as I understand the issue, I do have to properly combine the two lists in by within inner_fun(). Another attempt to do this was this:
outer_fun <- function(DT, by) {
# some other stuff
by <- substitute(by)
inner_fun(DT, by)
}
inner_fun <- function(DT, by) {
.by <- append(by, substitute(Plant), after = 0L)
DT[, .(mean = mean(uptake)),
by = eval(as.expression(list(.by)))]
}
outer_fun(CO2, by = Type)
This throws a similar error:
Error in `[.data.table`(DT, , .(mean = mean(uptake)), by = eval(as.expression(list(.by)))) :
column or expression 1 of 'by' or 'keyby' is type symbol. Do not quote column names. Usage: DT[,sum(colC),by=list(colA,month(colB))]
I'm struggeling here for two days now and I would really appreciate help on this!
EDIT:
It seems, I have not been clear on what the desired solution should be capable of. The result should work for all kinds of by which are allowed in data.table, such as:
outer_fun(CO2, by = Type)
outer_fun(CO2, by = "Type")
outer_fun(CO2, by = .(Type, Treatment))
outer_fun(CO2, by = c("Type", "Treatment"))
outer_fun(CO2, by = "Type,Treatment")
outer_fun(CO2, by = Treatment == "chilled")
outer_fun(CO2, by = cut(conc, breaks = quantile(conc)))
...