Reputation: 4474
I am trying to compare the result of which.max against 0 to check if any maximum value was found in the data. For explanation: There are about 24.000 vectors I must check for their maximum's index.
Here is a litte example:
tmp <- which.max(c(NA, NA, NA, NA))
str(tmp)
tmp == 0
as.integer(tmp) == 0
as.numeric(tmp) == 0
It results in FALSE, FALSE, and FALSE - although str(tmp) returns int(0).
What I did as workaround is this:
tmp <- which.max(c(NA, NA, NA, NA))
isTRUE(as.logical(tmp))
This works in differenetiation if which.max() found a maximum or not. However I do not understand why the above comparisons do not work.
Bonus question: Is there another function than str() that had easily shown me the tmp object's structure to instantly understand the comparison fail?
Thanks!
Upvotes: 1
Views: 878
Reputation: 40861
It would probably be better if which.max
returned 0
or -1
when no max value was found. Then you could more easily check it. regexpr
for instance returns -1
and match
allows you to specify what is returned in the case of no match (which this arguably is similar to).
...but you can check the return value's length yourself:
x <- which.max(c(NA, NA, NA, NA))
if(length(x)) {
# Do stuff with x...
}
...or wrap it into a function to simplify things:
which.max2 <- function(x) {
x <- which.max(x)
if(length(x)) x else 0L
}
which.max2(c(NA,-Inf,NA)) # 2
which.max2(c(NA,NA)) # 0
Upvotes: 2
Reputation: 176698
int(0)
means it's a zero-length vector (i.e. it has no elements, it's empty, etc.). Even if you do something like tmp == integer(0)
you get a zero-length logical vector, not TRUE
or FALSE
.
According to ?which.max
:
Value:
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’.
So you want to check to see whether length(tmp) > 0
.
Upvotes: 5