如果其中一个向量元素具有 NA 或不是 R 中的整数,如何使我的自定义函数 return 出现错误消息?

How do I make my custom function return an error message if one of the vector elements has NA or is not an integer in R?

我想要做的是一个函数,其中 x 是一个向量,y 是任何整数。如果 y 在向量 x 内,那么它应该 return "TRUE"。此外,如果向量包含 NA 或小数,则它应该打印一条错误消息。

到目前为止我已经创建了这个,但是如果我输入 search(c(9,8,3,NA),3) 它会给我这个消息:

Warning message:
In if (x%%1 != 0 | anyNA(x) == TRUE) { :
  the condition has length > 1 and only the first element will be used

如果像这样输入一个带有小数的向量search(c(8,9,7.01,12),12)它不会给出错误消息。

到目前为止,这是我的代码:

search <- function(x,y){
  if (x%%1!=0 | anyNA(x)==TRUE){
    print("ERROR")
  }else{
    if(y %in% x){
      print(TRUE)
    }
    else
      print(FALSE)
  }
}

使用sum(x %% 1) > 0验证x

search <- function(x,y){
     if (sum(x %% 1) | anyNA(x)==TRUE){
          stop("ERROR")
     }else{
          if(y %in% x){
               print(TRUE)
          }
          else
               print(FALSE)
     }
}

...输出:

> search(c(9,8,3,NA),3)
Error in search(c(9, 8, 3, NA), 3) : ERROR

> search(c(9,8,3),3)
[1] TRUE
>
> search(c(9,8,3),13)
[1] FALSE
> 

此外,最好使用 stop() 函数在 R 函数中传达错误。 stop() 停止执行当前表达式并执行错误操作。

如果您希望函数产生错误,请使用 stop,而不是 print。任何依赖该函数输出的程序都会保持 运行ning,而不会注意到任何错误。这可能会使以后的调试变得非常困难。 stop 抛出错误,然后可以适当处理。另外,因为如果满足条件该函数将退出,所以之后您不需要 else :如果不满足条件,该代码只会 运行 ,所以 else 是多余的。

你也可以简化一些逻辑。您不需要 if(condition == TRUE),因为 if(condition) 做同样的事情。最后,构造 if(condition){ print(TRUE) } else { print(FALSE) } 在逻辑上等同于 print(condition)

search <- function(x, y){
  if (any(x %% 1 != 0) | anyNA(x) | length(y) != 1) stop("Error")
  y %in% x
}

现在在测试用例上试试:

search(c(1, 3, 5), 3)
#> [1] TRUE
search(c(1, 3, 5), 2)
#> [1] FALSE
search(c(1, 3, NA), 3)
#> Error in search(c(1, 3, NA), 3): Error
search(c(1, 3, 5.1), 3)
#> Error in search(c(1, 3, 5.1), 3): Error
search(c(1, 3, 5), c(1, 3))
#> Error in search(c(1, 3, 5), c(1, 3)): Error

reprex package (v0.3.0)

于 2020-05-15 创建