Assume a numeric vector x <- c(-3,2,1,-2, 4,-1,-5)
Min non-negative value in x
is 1
so the index/location/answer should be 3
.
How can we do it by using any function?
(Note: Function which.min
, in the above case, gives answer/index 7
that is the minimum (but not non negative))
You can use
which.max(1 / x)
# [1] 3
Try:
which(x==min(x[x>0]))
#[1] 3
it tells R
to search for the x
that is equal to the minimum of non-negative values.
Edit: In case of multiple minima, it will display all of them, so in this case, you can do min(which(x==min(x[x>0])))
.
NB: in this case, you cannot use which.min
as which.min(x[x>0])
would give you the index of the minimum value in the vector x[x>0]
(2
here)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With