我有一个公式作为字符向量,想在curve
中使用它。
curve(-8*cos(2*x), 0, 10) #works as expected
formula <- "-8*cos(2*x)"
# nothing works
curve(formula, 0, 10)
# Error in formula.default(x) : invalid formula
curve(eval(formula), 0, 10)
# Error in curve(eval(formula), 0, 10) :
# 'expr' must be a function, or a call or an expression containing 'x'
curve(as.expression(formula), 0, 10)
# Error in curve(as.expression(formula), 0, 10) :
# 'expr' must be a function, or a call or an expression containing 'x'
curve(eval(as.expression(formula)), 0, 10)
# Error in curve(eval(as.expression(formula)), 0, 10) :
# 'expr' must be a function, or a call or an expression containing 'x'
curve(parse(text = formula), 0, 10)
# Error in curve(parse(text = formula), 0, 10) :
# 'expr' must be a function, or a call or an expression containing 'x'
curve(eval(parse(text = formula)), 0, 10)
# Error in curve(eval(parse(text = formula)), 0, 10) :
# 'expr' must be a function, or a call or an expression containing 'x'
我的问题
我该如何工作?
最佳答案
一种可能性是简单地包装一个函数,
curve((function(x) eval(parse(text=formula)))(x), 0, 10)
关于r - 如何在公式()中将公式用作字符向量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35997467/