Finding the index of the nonzero minimum value in R

Viewed 200
bado<-c(0,2,1,2,3,4,1,0,0,2)
bado
which.min(bado[bado>0])

Hi, I want to find the index of the nonzero minimum value. I tried which.min function but which.min disregards the index of the zeros when counting indexes. In my code. min output should be 3 but it gives 2 as an output. How can I solve this? What should I use to find the real index?

3 Answers

Maybe you can try the code below

inds <- bado>0
seq_along(bado)[inds][which.min(bado[inds])]

where

  • seq_along(bado)[inds] gives the indices of non-zero values
  • which.min(bado[inds]) gives the index of minimum non-zero value

An option is to replace the values that are less than or equal to 0 to a higher value and then use which.min

which.min(replace(bado, bado <=0, max(bado) + 1))
#[1] 3

Or replace it to NA and then wrap with which.min

which.min(replace(bado, bado <= 0, NA))
#[1] 3

NOTE: The replace is not changing the original object bado


Or a slightly more compact option is

which.min(NA^(bado <= 0) * bado)
#[1] 3

You can use :

which.max(bado == min(bado[bado>0]))
#[1] 3

min(bado[bado>0]) will return the minimum value greater than 0. We compare this value with bado (bado == min(bado[bado>0])) and return the first index where the value occurs.

Related