我正在尝试围绕 CVXR 编写一个包装函数,以便函数可以传递“目标”和“约束”。我使用以下示例:
例子:
x1 <- Variable(1) # a scalar
x2 <- Variable(1) # a scalar
objective <- Minimize( x1^2 + x2^2 )
constraints <- list(x1 <= 0, x1 + x2 == 0)
problem <- Problem(objective, constraints)
## Checking problem solution
solution <- solve(problem)
到目前为止我的尝试:
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars = c("x1", "x2")
obj = "x1^2 + x2^2"
const = "(x1 <= 0, x1 + x2 == 0)"
for(i in 1:length(vars)) {assign(vars[i], Variable(1, name = vars[i]))}
objective <- eval(paste("Minimize(", obj, ")"))
}
问题:
目标变量的计算结果不是 x1^2 + x2^2,而是带有引号。我试过 as.formula、eval、substitute 等。