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
max
uses all values in all arguments passed to max(...)
, so:
max(which(ff == my.index), 0)
#[1] 0