Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of minimum non negative value in R

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))

like image 778
Navin Manaswi Avatar asked Oct 15 '25 16:10

Navin Manaswi


2 Answers

You can use

which.max(1 / x)
# [1] 3
like image 177
Sven Hohenstein Avatar answered Oct 17 '25 05:10

Sven Hohenstein


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)

like image 38
Cath Avatar answered Oct 17 '25 05:10

Cath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!