I am trying to use eval() function in R to calculate expressions.
I am retrieving the the formula from a data frame and storing it in a variable say 'form'.
Now I tried to evaluate this expression as follows:
df
x y z
1 2 3
4 5 6
7 8 9
form = "x+y+z"
expr = expression(form)
df = data.table::data.table(df)
result = eval(expr, df[1])
I am getting the result as "x+y+z" instead of 6.
If I directly pass the formula in to the expr = expression(..), I get the correct result, but I couldn't do that coz I am retrieving the formula from other data frame. Please suggest.
expression doesn’t do what you think it does. You need to use parse instead:
expr = parse(text = form)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With