所以我正在开发这个功能
#' Disambiguated Equality operator between two vectors that may contain NA's
#'
#' Forces the equality result to be TRUE if both corresponding vector elements are either equal, or both NA.
#' @param x vector of any type compatible with is.na and ==.
#' @param y vector of any type compatible with is.na and ==.
#' @export
#' @examples
#' c(NA, 1:5) %==% c(NA, 1:3,"nope", NA) #[1] TRUE TRUE TRUE TRUE FALSE FALSE
gp.is.equal.force <- `%==%` <- function(x, y, vect = T) {
res <- (is.na(x) & is.na(y)) | (!is.na(x) & !is.na(y) & x == y)
if (!vect) res <- all(res)
res
}
我注意到 R 版本 4.3.2 (2023-10-31) 上的 NaN 值出现了我没有预料到的行为——“Eye Holes”。
> is.na(NaN) # [1] TRUE
> is.na(c(NaN, 5)) # [1] TRUE FALSE
> is.na(c(NaN, NA)) # [1] TRUE TRUE
> is.nan(c(NaN, NA)) # [1] TRUE FALSE
> is.na(c(NaN, as.factor("abc"))) # [1] TRUE FALSE
> is.nan(c(NaN, 5)) # [1] TRUE FALSE
到目前为止一切都很好,但是:
> is.na(c(NA, NaN, "abc")) # [1] TRUE FALSE FALSE
> is.nan(c(NA, NaN, "abc")) # [1] FALSE FALSE FALSE
> is.nan(c(NaN, "abc")) #[1] FALSE FALSE
似乎将character
s 添加到混合中会以某种方式破坏值的逻辑NaN
。是不是很奇特?
从
?NaN
(我大胆的),将字符添加到向量中会将该向量强制转换为字符类型,因此
NaN
不再表示“不是数字”,而是字符“NaN”。正如预期的那样,
is.nan
将返回FALSE
字符。