【问题标题】:Plot function with else if statement in R在 R 中使用 else if 语句绘制函数
【发布时间】:2018-02-28 22:15:18
【问题描述】:

试图在区间 [-1,1] 上绘制以下函数,但出现错误代码:

"Warning messages:
1: In if (g < a) { :
the condition has length > 1 and only the first element will be used
2: In if (g >= a & g <= b) { :
the condition has length > 1 and only the first element will be used"

unifCDF<-function(g) {
  if (g< a) {
    0
  }
  else if (g>=a & g<=b) {
    (g-a)/(b-a)
  }
  else if (g>b) {
    1
  }
}

我知道函数本身有效,因为 unifCDF() 适用于我测试的所有值。有什么想法吗?

【问题讨论】:

  • ab 定义在哪里,你传递给 unifCDF() 函数的类型是什么?
  • a = -1 b = 1,而unifCDF是g的函数
  • if 用于将一个值与另一个值进行比较。 if(2 &gt; 1) print("yes") - 不用于比较多个值。例如。 if(2 &gt; c(1,2,3)) print("yes") 发出警告并仅给出第一次比较的结果。
  • 我使用了 plot.function(unifCDF,from=a,to=b)
  • "条件的长度 > 1,并且只会使用第一个元素" - 这与我在尝试比较向量而不是单个值时遇到的错误相同。跨度>

标签: r function if-statement plot


【解决方案1】:

您的函数适用于单个值:

> unifCDF(.5)
[1] 0.75

但不在向量上:

> unifCDF(c(0.2,.3))
[1] 0.60 0.65
Warning messages:
1: In if (g < a) { :
  the condition has length > 1 and only the first element will be used
2: In if (g >= a & g <= b) { :
  the condition has length > 1 and only the first element will be used

并且 plot.function 需要函数来处理向量。懒惰的方法是 Vectorize 你的函数:

> unifCDF=Vectorize(unifCDF)
> unifCDF(c(0.2,.3))
[1] 0.60 0.65
> plot.function(unifCDF,-1,1)

然后工作。

正确的方法是对其进行编码,使其自然地处理向量参数。

unifCDF = function(g){
   res = (g-a)/(b-a)
   res[g<a]=0
   res[g>b]=1
   res
}

在此代码中,res 始终是与g 长度相同的向量。第一行计算 g 的所有值的斜率位,然后接下来的两行将 (a,b) 限制之外的相关位设置为 0 和 1。

请注意,拥有像 ab 这样的全局变量通常是一件坏事。

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 2020-11-20
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多