3

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.

der_grund
  • 1,898
  • 20
  • 36
  • 5
    This is a classic and has been asked dozens if not hundreds of times before. You are looking for `parse / eval`: `df[, (new_var) := eval(parse(text=..expression))]`. This structure is typically discouraged and typically implies that you should rethink what you are trying to do. – lmo May 29 '18 at 09:44
  • Thanks for the quick reply. Can you give a hint on why exactly this is discouraged? I need to extract the expressions from a character column of a data.frame and do not have another idea. – der_grund May 29 '18 at 10:24
  • 2
    Probably take a look at [this post](https://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse) regarding `parse` and `eval`. It is a good starting point. – lmo May 29 '18 at 10:31
  • I didn't check your previous question :-) – akrun May 29 '18 at 15:37

0 Answers0