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.