[最近,我在我的R代码中发现了一个错误,该错误是由R的自动强制引起的。我不小心将一个字符串向量与一个整数进行比较,并且该代码在大多数正确的比较下都能成功运行,这使得很难首先知道错误。所以我想知道有什么我可以做的事来禁用此自动强制并引发错误,就像python一样。
这是R比较两个类型不同的变量的方式:
如果两个参数是不同类型的原子向量,则一个被强制转换为另一个,而优先级的降序是字符,复数,数字,整数,逻辑和原始。
例如,
'95'>90
#[1] TRUE
'100'>90
#[1] FALSE
您应该做的是在比较之前检查参数的类型。假设您有一个类似的功能:
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
但是,再次,不要在家中尝试此操作(也不要在更大范围内尝试)。