简体   繁体   中英

R - extract variable names from unevaluated expression

Assume following model

目标1

目标2

进球3

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, eg

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 to expression() , whose value is the (unevaluated) call y + 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):

> as.list(expression(x=y+z))
$x
y + z

> names(expression(x=y+z))
[1] "x"

If, OTOH, you use the formula constructor ~ , then you get the LHS as a part of the expression:

> as.list(expression(x~y+z))
[[1]]
x ~ y + z

And you can get to it selecting the second element of the call:

> expression(x~y+z)[[1]]
x ~ y + z
> expression(x~y+z)[[1]][[1]]
`~`
> expression(x~y+z)[[1]][[2]]
x

Note: in the last line, x is a symbol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM