Home > Enterprise >  max returns negative infinity in R
max returns negative infinity in R

Time:08-27

I have stumbled upon a seemingly simple problem which I just cannot solve. I am attempting to use max and which on a vector that does not contain the value of interest. Ideally I would like to obtain the number 0 in that instance. But I keep getting negative infinity.

ff <- c(2, 4, 6, 8, 10)
my.index <- 1
max(which(ff == my.index))
#[1] -Inf
#Warning message:
#In max(which(ff == my.index)) :
#  no non-missing arguments to max; returning -Inf

Here are some other attempts that return the same result:

max(as.numeric(which(ff == my.index)))
max(which(ff == my.index), na.rm = TRUE)
max(as.numeric(which(ff == my.index)), na.rm = TRUE)
max(numeric(0))

I did notice:

max(0)
[1] 0

So, I thought maybe the simplest solution would be to convert -Inf to 0. Is there a more elegant base R solution than the one below? A one-liner? Ideally one that would not return a warning message?

aaa <- max(which(ff == my.index))
aaa[is.infinite(aaa)] <- 0
aaa
[1] 0

CodePudding user response:

max uses all values in all arguments passed to max(...), so:

max(which(ff == my.index), 0)
#[1] 0

CodePudding user response:

On how to do it, thelatemail has already given you an answer, just pass an extra default value as an argument. But I would add the reason why you are getting -Inf.

Since there are no elements in ff with a value of 1, which(ff == my.index) returns integer(0) which is not the same as 0. It is an empty object of class integer.

Since any integer is the greatest in a set which contains only that integer it makes sense to consider that the max function returns -Inf since if you have two sets (vectors in R) A and B, max(A, B) = max(max(A), max(B)). So if A is empty and B is not, max(A,B) = max(B), but this was equal to max(max(A), max(B)), which implies that max(B) > max(A) for any integer, so in order to follow this R assigns the value of -Inf to max(integer(0)).

  • Related