首页 文章

R:用户定义函数中此错误消息的含义是什么?

提问于
浏览
0

我正在编写一个家庭作业问题,要求我编写一个函数,根据输入数据绘制不同类型的图表 .

该函数的参数是 xytype ,其中 xy 是我想要绘制的矢量, type 是绘图的类型(散点图,方框或直方图) .

需要编写该函数,以便在没有为类型为scatterplot的 x 指定数据时,会收到一条错误消息,指出您需要x数据来制作散点图 .

同样,如果您使用直方图或boxplot类型为 x 指定数据,则会收到一条错误消息,指出您只需要这些绘图类型的y数据 .

我有一个函数编写,生成正确的图形和错误消息,但也给了我一个 warning message

In if (y == FALSE & type == 1) { :
   the condition has length > 1 and only the first element will be used

功能如下 . 有人能告诉我为什么我会收到这个特别的警告吗?

plot.function2=function(x=FALSE,y=FALSE,type){
  if(x==FALSE & type==1){
    stop("Error Message 1")
  }else if (y==FALSE & type==1){
    stop("Error Message 1.5")
  }else if(type==1){
    plot=plot(y~x) 
  }else if (x==TRUE & type==2){
    stop("Error Message 2")
  }else if(type==2){
    plot=boxplot(y)
  }else if(type==3){
    plot=barplot(y)
  }

plot
}

该消息显示大多数输入;例如,输入 plot.function2(v1, v2, 1) 会得到两个向量的散点图, but also 警告消息 . 谢谢!

1 回答

  • 2

    您正在使用函数将向量与布尔值进行比较 .

    # Here if you provide a vector x, you are essentially checking
    # if each element is TRUE, hence the warning
    
      if(x==FALSE & type==1){
        stop("Error Message 1")
      }
    

    例如,请参阅虹膜数据集中的矢量

    > iris[1:25,1] == TRUE
     [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
    

    您应该使用 NULLis.null 来查看对象是否为空

    plot.function2=function(x=NULL,y=NULL,type){
      if(is.null(x) & type==1){
        stop("Error Message 1")
      }else if (is.null(y) & type==1){
        stop("Error Message 1.5")
      }else if(type==1){
        plot=plot(y~x) 
      }else if (is.null(x) & type==2){
        stop("Error Message 2")
      }else if(type==2){
        plot=boxplot(y)
      }else if(type==3){
        plot=barplot(y)
      }
    plot
    }
    

    根据建议,可以使用 switch 语句进行清理,如您所见 .

    plot.function2=function(x=NULL,y=NULL,type){  
      # check if nulls
      if(is.null(y)){
        stop("You need to provide y data!!!")
      }
      if(is.null(x) & type == 1){
        stop("You need to provide x data!!!")
      }
    
      plot <- switch(as.character(type),
                     "1" = plot(y~x),
                     "2" = boxplot(y),
                     "3" = barplot(y))
      plot
    }
    

相关问题