I want to write a function that has two inputs: The name of a new variable and a mathematical expression. Both arguments come as strings.
This function should take a data.table
and add the specified new variable which should be the result of the given mathematical expression.
This is a minimal working example of what I tried:
library(data.table)
df <- data.table(A = 1:10, B = 1:10)
new_var <- "C"
expression <- "A + B"
example_fun <- function(new_var, expression) {
DT[, (new_var) := expression]
}
example_fun(new_var, expression)
> DT
A B C
1: 1 1 A + B
2: 2 2 A + B
3: 3 3 A + B
4: 4 4 A + B
5: 5 5 A + B
6: 6 6 A + B
7: 7 7 A + B
8: 8 8 A + B
9: 9 9 A + B
10: 10 10 A + B
I get the same result when I use DT[, (new_var) := (expression)]
or DT[, (new_var) := .(expression)]
inside the function.
From what I understand, I somehow need to tell data.table
that expression
should not be evaluated as a string but as an expression. I know that I can use get()
for accessing single variables using a string but this does not work with several variables at once.