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.

4
  • 1
    This is due to non standard evaluation of j argument, see. 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. Commented Sep 3, 2022 at 7:46
  • 1
    @Waldi Thanks for the link. I had not seen that question. Commented Sep 3, 2022 at 8: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. Commented Sep 4, 2022 at 17:52
  • 1
    @jangorecki Thanks for your help and thanks also for your work on data.table. Commented Sep 5, 2022 at 19:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.