如何用方程中的变量替换另一个方程,然后在 R 中计算这个表达式?

How do I substitute a variable in an equation for another equation & then evaluate that expression in R?

我的问题很简单,但我还没有找到解决办法。我有等式 y = 3 + x & x = x1 + x2;其中 x1 = 3 & x2 = 4。这些方程式来自文本文件。不出所料,我希望 y 等于 10。我尝试了以下方法,但显然不起作用。

x1 <- 3
x2 <- 4
y_equation <- "3 + x"
x_equation <- "x1 + x2"
y <- parse(text = y_equation)
y <- substitute(y, list(x = parse(text = x_equation)))
eval(y)

非常感谢任何帮助。

我们可以使用sub将'y_equation'中的'x'替换为'x_equation',然后执行eval

eval(parse(text = sub("x", x_equation, y_equation)))
#[1] 10