Return index of the smallest value in a vector?

R

R Problem Overview


a <- c(1, 2, 0, 3, 7)

I am looking for a function to return the index of the smallest value, 3. What is it?

R Solutions


Solution 1 - R

You're looking for which.min():

a <- c(1,2,0,3,7,0,0,0)
which.min(a)
# [1] 3

which(a == min(a))
# [1] 3 6 7 8

(As you can see from the above, when several elements are tied for the minimum, which.min() only returns the index of the first one. You can use the second construct if you instead want the indices of all elements that match the minimum value.)

Solution 2 - R

As an alternative to Josh's answer

a <- c(1, 2, 0, 3, 7)
which(a == min(a))

this gives every index that is equal to the minimum value. So if we had more than one value matching the lowest value

a <- c(1, 2, 0, 3, 7, 0)
which(a == min(a))  # returns both 3 and 6
which.min(a)        # returns just 3

Edit: If what you're looking for is just how many elements are equal to the minimum (as you imply in one of the comments) you can do this instead:

a <- c(1, 2, 0, 3, 7, 0)
sum(a == min(a))

Solution 3 - R

If you are a fan of efficiency, then you can use the function min_max from the Rfast package, with index = True

It will return the index of the minimum and the index of the maximum value, simultaneously, faster than what has been disused so far.

E.g.

a = runif(10000)
Rfast::min_max(a,index=T)

# min  max 
# 2984 2885

which(a == min(a))

#[1] 2984

a = runif(1000000)
microbenchmark::microbenchmark(
    min_max = Rfast::min_max(a,index=T),
    which1 = which(a == min(a)),
    which2 = which.min(a)
)

Unit: milliseconds
   expr      min         lq        mean     median         uq        max neval
min_max 1.889293  1.9123860  2.08242647  1.9271395  2.0359730   3.527565   100
 which1 9.809527 10.0342505 13.16711078 10.3671640 14.7839955 111.424664   100
 which2 2.400745  2.4216995  2.66374110  2.4471435  2.5985265   4.259249   100

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhhhView Question on Stackoverflow
Solution 1 - RJosh O'BrienView Answer on Stackoverflow
Solution 2 - RDasonView Answer on Stackoverflow
Solution 3 - RStefanosView Answer on Stackoverflow