Assume following model
is written in a text file by someone not familiar with R as follows:
goal1 = dec1_g1 + dec2_g1 + dec3_g1
goal2 = min(dec1_g2, dec2_g2, dec3_g2)
goal3 = dec1_g3 - dec2_g3 - dec3_g3
...
I need to be able to parse the text file with the model and evaluate any one line without having to assign values to the dec variables from the remaining lines of the model. While the parse
function creates an unevaluated expression exp
that can be queried and evaluated in parts as eval(exp[1]), eval(exp[2])
, I haven't found a way to do something like eval(exp['goal1'])
.
Question: is there a way to parse the model without evaluating it and create a list with elements named by the left-hand sides of the model expressions, e.g.
model = list(
"goal1" = expression(goal1 = dec1_g1 + dec2_g1 + dec3_g1),
"goal2" = expression(goal2 = min(dec1_g2, dec2_g2, dec3_g2)),
"goal3" = expression(goal3 = dec1_g3 * dec2_g3 * dec3_g3),
...
)
Motivation: I want to be able to load the model from within an R code, parse it and evaluate it expression by expression assigning correct values to the dec variables depending no the goal that's being evaluated.
The "left hand side" of
expression(x=y+z)
is actually the name of the argument you're passing toexpression()
, whose value is the (unevaluated) cally + z
. So it's not a part of the expression, but is returned as the name of the list element (an expression is a list of calls, usually unnamed):If, OTOH, you use the formula constructor
~
, then you get the LHS as a part of the expression:And you can get to it selecting the second element of the call:
Note: in the last line,
x
is a symbol.