为什么我不能测试which.max()对0

Bur*_*Leo 1 r

我试图比较which.max与0的结果,以检查数据中是否找到任何最大值.解释:我必须检查大约24.000个向量的最大索引.

这是一个小例子:

tmp <- which.max(c(NA, NA, NA, NA))
str(tmp)
tmp == 0
as.integer(tmp) == 0
as.numeric(tmp) == 0
Run Code Online (Sandbox Code Playgroud)

它导致FALSE,FALSE和FALSE - 尽管str(tmp)返回int(0).

我做的解决方法是:

tmp <- which.max(c(NA, NA, NA, NA))
isTRUE(as.logical(tmp))
Run Code Online (Sandbox Code Playgroud)

如果which.max()找到了最大值,则可以在不同的情况下工作.但是我不明白为什么上述比较不起作用.

额外的问题:是否有另一个函数比str()更容易向我展示tmp对象的结构,以便立即理解比较失败?

谢谢!

Jos*_*ich 5

int(0)意味着它是一个零长度的向量(即它没有元素,它是空的,等等).即使你做了像你这样的事情,tmp == integer(0)你得到一个零长度的逻辑向量,而不是TRUEFALSE.

根据?which.max:

值:

 Missing and ‘NaN’ values are discarded.

 an ‘integer’ of length 1 or 0 (iff ‘x’ has no non-‘NA’s), giving
 the index of the _first_ minimum or maximum respectively of ‘x’.
Run Code Online (Sandbox Code Playgroud)

所以你想检查是否length(tmp) > 0.