0

I'm having trouble with an "object not found" error when defining a function involving the data.table cube() function. An example is given below. I'm using data.table 1.14.2 in R 4.2.1.

library(data.table)

f <- function(values, dec_places) {
  round(sum(values), digits = dec_places)
}

DT <- data.table(x = c("a", "a", "b", "b"),
                 y = c(1.101, 1, 2.101, 1))

DT
#    x     y
# 1: a 1.101
# 2: a 1.000
# 3: b 2.101
# 4: b 1.000

x_var <- "x"
y_var <- "y"
dp <- 1

# This works:
cube(DT, f(get(y_var), dec_places = dp), by = x_var)
#       x  V1
# 1:    a 2.1
# 2:    b 3.1
# 3: <NA> 5.2

# But I want to put this in a function:
g <- function(Data, num_var, group_var, decimal_places) {
  cube(Data, f(get(num_var), dec_places = decimal_places), by = group_var)
}

g(Data = DT, num_var = y_var, group_var = x_var, decimal_places = dp)
# Error in get(num_var) : object 'num_var' not found

Why does this error happen and how should I change the function g to fix it?

Thanks.

mark999
  • 175
  • 7
  • 1
    This is due to non standard evaluation of `j` argument, [see](https://stackoverflow.com/a/59623006/13513328). However, the workaround presented in the previous link won't work here due to `dec_places` argument which will be difficult to pass as name. – Waldi Sep 03 '22 at 07:46
  • 1
    @Waldi Thanks for the link. I had not seen that question. – mark999 Sep 03 '22 at 08:30
  • 1
    You can use `groupingsets` function and its `jj` argument. Then you just substitute in your function call to `j` and pass it to `jj`. Check manual. – jangorecki Sep 04 '22 at 17:52
  • 1
    @jangorecki Thanks for your help and thanks also for your work on data.table. – mark999 Sep 05 '22 at 19:22

0 Answers0