我只是好奇为什么这个语句在 R 中会返回一个错误
> curve(function(x) x^2, from = -2, to = 2)
##Error in curve(function(x) x^2, from = -2, to = 2) :
#'expr' did not evaluate to an object of length 'n'
我知道这个语句完美地工作。
> curve(x^2, from = -2, to = 2)
据我所知,R中函数curve()的第一个参数应该是矢量化函数。因此,function(x) x^2作为参数也应该是矢量化函数,因为它返回一个数值向量,其长度等于输入数值向量的长度。
然而,我不能确定,因为我在编程方面没有严格的背景。显然,我是错的。
curve
中的第一个参数expr=
是在寻找一个函数的名称,而不是一个函数本身。因此,它需要在外部进行声明-f <- function(x) x^2; curve(f, from=-2, to=2)
。否则,您可以直接使用plot
绘制函数plot(function(x) x^2, xlim=c(-2,2))
。 - thelatemailplot
,它将使用方法plot.function
。 - kjetil b halvorsen