Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval() function in R

Tags:

r

eval

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.

like image 693
R Bud Avatar asked Dec 14 '25 15:12

R Bud


1 Answers

expression doesn’t do what you think it does. You need to use parse instead:

expr = parse(text = form)
like image 151
Konrad Rudolph Avatar answered Dec 17 '25 11:12

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!