【问题标题】:Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab, : 'expr' did not evaluate to an object of length 'n'曲线错误(expr = x,from = from,to = to,xlim = xlim,ylab = ylab,:'expr' 未计算为长度为 'n' 的对象
【发布时间】:2021-01-30 06:48:57
【问题描述】:

我想绘制以下分段函数,但我不断收到错误

a <- function(x) {ifelse(( x < -1), 0, ifelse((-1 < x & x < 2),(x^3 + 1)/9, ifelse((x > 2), 1, NA))) } 
 plot(a, xlim=c(-5, 5), ylim = c(-4, 7), col = "red") 
 abline(v = 0, h = 0)

【问题讨论】:

  • 您的意思是x &lt;=1?还是x &lt; -1?您可能会收到此错误,因为&lt;- 在 R 中作为赋值运算符具有含义。

标签: r plot error-handling curve


【解决方案1】:

您的代码几乎是正确的,但添加空格以使其可读会有所帮助。正如@Phil 提到的那样触发错误,因为x&lt;-1 被R 解释为“将1 的值赋给x”。您正在使用 plot 命令的版本来绘制函数,该版本与 curve 函数一起记录(请参阅 ?curve)。您可能应该包含 from=to= 参数,但该函数将使用没有它们的 xlim 值:

a <- function(x){ ifelse(( x < -1), 0, ifelse((-1 < x & x < 2),(x^3 + 1)/9, ifelse((x > 2), 1, NA))) }
plot(a, from=-5, to=5, n=201, xlim=c(-5, 5), ylim = c(-4, 7), col = "red")
abline(v = 0, h = 0, lty=3)

注意添加到您的plot() 命令。我将abline 更改为使用虚线,使功能更易于查看。添加n=201 会增加直线中的点数,因此曲线更平滑,线段之间的间隙更小。

【讨论】:

    猜你喜欢
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多