比较不同类型时,有没有办法在 R 中禁用自动强制

Is there a way to disable auto coercion in R when comparing different types

最近,我在我的 R 代码中发现了一个错误,这是由 R 的自动强制转换引起的。我不小心将一个字符串向量与一个整数进行了比较,代码成功运行了大部分正确的比较,这使得它一开始就很难知道错误。所以我想知道我能做些什么来禁用这种自动强制并引发错误,就像 python 所做的那样。

这是 R 比较两个不同类型的变量的方式:

如果两个参数是不同类型的原子向量,一个被强制转换为另一个的类型,优先级(递减)顺序为字符、复数、数字、整数、逻辑和原始。

例如,

'95'>90 
#[1] TRUE
'100'>90
#[1] FALSE

原则上,可以覆盖 R 中的每个基本运算符。但这样做非常危险,因此我基本上不会在任何情况下推荐。

你应该做的是在比较之前检查参数的类型。比如说你有一个这样的函数:

f <- function(arg1, arg2, ...) {
   #here you do some stuff
   x <- something(arg1)
   y <- someotherthing(arg1, arg2)
   #here you are about to do the comparison
   #but you check the arguments beforehand
   if (typeof(x)!=typeof(y)) stop("Type mismatch")
   #if there isn't any error you continue
   z <- x > y
   ...
   return(somevalue)
}

重新定义基本运算符的危险方法怎么样?这是:

`>`<-function(e1, e2) {
    if (typeof(e1)!=typeof(e2) && (!is.numeric(e1) || !is.numeric(e2)) ) stop("Type mismatch")
    basegt<-get(">",baseenv())
    basegt(e1,e2)
}
'95'>90 
#Error in "95" > 90 : Type mismatch
95>90
#[1] TRUE

但是,再次强调,不要在家里尝试这个(更不要在工作中尝试)。