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

R:在用户定义函数中,此错误消息的含义是什么?,r,R,我正在做一个家庭作业,要求我写一个函数,根据输入数据绘制不同类型的图 函数的参数是x,y,和类型,其中x和y是我想要绘制的向量,类型是绘制的类型(散点、方框或直方图) 该函数需要编写,这样,如果您没有使用scatterplot类型为x指定数据,就会收到一条错误消息,说明您需要x数据来生成scatterplot 同样,如果您确实使用类型直方图或箱线图为x指定数据,则会收到一条错误消息,说明这些打印类型只需要y数据 我编写了一个函数,它可以生成正确的图形和错误消息,但也会给我一条警告消息: In i

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

函数的参数是
x
y
,和
类型
,其中
x
y
是我想要绘制的向量,
类型
是绘制的类型(散点、方框或直方图)

该函数需要编写,这样,如果您没有使用scatterplot类型为
x
指定数据,就会收到一条错误消息,说明您需要x数据来生成scatterplot

同样,如果您确实使用类型直方图或箱线图为
x
指定数据,则会收到一条错误消息,说明这些打印类型只需要y数据

我编写了一个函数,它可以生成正确的图形和错误消息,但也会给我一条警告消息

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)
会得到两个向量的散点图,但也会得到警告消息。谢谢

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

# 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数据集中的向量

> 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
您应该使用
NULL
is.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
}
plot.function2=function(x=NULL,y=NULL,type){
#检查是否为空
如果(为空(y)){
停止(“您需要提供y数据!!!”)
}
if(is.null(x)&type==1){
停止(“您需要提供x数据!!!”)
}

如果
/
否则
读起来很痛苦,请绘制嵌套的
。查看
开关
函数。您可以根据类型进行切换,并在切换后测试输入有效性。您不需要
is.null(x)==TRUE
,只需
is.null(x)
即可。