我有一个功能NA
作为默认值,但如果没有NA
应该是一个不限于大小 1 的字符向量。我有一个检查来验证这些,但是is.na
当向量是字符向量时产生标准警告length
大于1。
so_function <- function(x = NA) {
if (!(is.na(x) | is.character(x))) {
stop("This was just an example for you SO!")
}
}
so_function(c("A", "B"))
#> Warning in if (!(is.na(x) | is.character(x))) {: the condition has length >
#> 1 and only the first element will be used
防止我提出的警告的一个选项是使用identical
:
so_function <- function(x = NA) {
if (!(identical(x, NA) | is.character(x))) {
stop("This was just an example for you SO!")
}
}
我的问题是,这个函数通常会将加载到 R 中的 Excel 工作表数据作为输入,并且NA
由此产生的值通常是NA_character_
, NA_integer_
, and NA_real_
, so identical(x, NA)
经常FALSE
当我真正需要它的时候TRUE
.
对于更广泛的背景,我在为包创建的 S3 类中遇到了这个问题,下面的函数近似于我验证该类的多个属性的方式,也就是出现警告时。因此,我试图避免将抑制警告作为解决方案,因此有兴趣了解解决此问题的最佳实践。
Edit
为了使用例更清晰,这是验证类的属性,我想确保该属性是单个NA
值,或任意长度的字符向量:
so_function(NA_character_) # should pass
so_function(NA_integer_) # should pass
so_function(c(NA, NA)) # should fail
so_function(c("A", "B")) # should pass
so_function(c(1, 2, 3)) # should fail