我有一个公式作为字符向量,并希望在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'
我的问题
我怎样才能做到这一点?
答案 0 :(得分:2)
一种可能性是简单地用函数包装,
curve((function(x) eval(parse(text=formula)))(x), 0, 10)