在R中绘制图形时生成序列时出错

时间:2017-10-26 07:15:28

标签: r plot seq

只是尝试生成一个函数,用于绘制曲线下面积为z得分或一组z得分的区域,但是当我用zshade(c(1,2))给出两个z得分时,我得到以下错误:

Error in seq.default(z1, z2, 0.01) : 'to' must be of length 1

但我不确定为什么会出现这种情况,我仔细检查了z2,确实长度为1,所以我不确定错误在哪里。

zshade = function(z, shade = "left") {
  # If more than 2 z scores are given
  if (length(z) > 2) {
    stop("Error: Too many z scores given!")
  }

  # If two z scores are given
  if (length(z) > 1) {
    z1 = min(z)
    z2 = max(z)
    cord.x = c(z1, seq(z1, z2, 0.01), z2)
    cord.y = c(0, dnorm(seq(z1, z2, 0.01)), 0)
    curve(dnorm(x, 0, 1), xlim = c(-4, 4), main = "Standard Normal", 
      ylab = "", xlab = "")
    polygon(cord.x, cord.y, col = "skyblue")
  }

  # If a single z score is given
  if (shade == "left") {
    z1 = -4
    z2 = z
    cord.x = c(z1, seq(z1, z2, 0.01), z2)
    cord.y = c(0, dnorm(seq(z1, z2, 0.01)), 0)
    curve(dnorm(x, 0, 1), xlim = c(-4, 4), main = "Standard Normal Curve", 
        ylab = "", xlab = "")
    polygon(cord.x, cord.y, col = "skyblue")
  }
  if (shade == "right") {
    z1 = z
    z2 = 4
    cord.x = c(z1, seq(z1, z2, 0.01), z2)
    cord.y = c(0, dnorm(seq(z1, z2, 0.01)), 0)
    curve(dnorm(x, 0, 1), xlim = c(-4, 4), main = "Standard Normal Curve", 
        ylab = "", xlab = "")
    polygon(cord.x, cord.y, col = "skyblue")
  }
}

zshade(C(1,2))

1 个答案:

答案 0 :(得分:0)

愚蠢的错误,请参阅下面的代码......

zshade = function(z, shade = "left") {
# If more than 2 z scores are given
if (length(z) > 2) {
  stop("Error: Too many z scores given!")
}

# If two z scores are given
if (length(z) > 1) {
  z1 = min(z)
  z2 = max(z)
  cord.x = c(z1, seq(z1, z2, 0.01), z2)
  cord.y = c(0, dnorm(seq(z1, z2, 0.01)), 0)
  curve(dnorm(x, 0, 1), xlim = c(-4, 4), main = "Standard Normal", 
        ylab = "", xlab = "")
  polygon(cord.x, cord.y, col = "skyblue")
}

if (length(z)==1) {
  # If a single z score is given
  if (shade == "left") {
    z1 = -4
    z2 = z
    cord.x = c(z1, seq(z1, z2, 0.01), z2)
    cord.y = c(0, dnorm(seq(z1, z2, 0.01)), 0)
    curve(dnorm(x, 0, 1), xlim = c(-4, 4), main = "Standard Normal Curve", 
          ylab = "", xlab = "")
    polygon(cord.x, cord.y, col = "skyblue")
  }
  if (shade == "right") {
    z1 = z
    z2 = 4
    cord.x = c(z1, seq(z1, z2, 0.01), z2)
    cord.y = c(0, dnorm(seq(z1, z2, 0.01)), 0)
    curve(dnorm(x, 0, 1), xlim = c(-4, 4), main = "Standard Normal Curve", 
          ylab = "", xlab = "")
    polygon(cord.x, cord.y, col = "skyblue")
  }
 }
}