Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return index of the smallest value in a vector?

Tags:

r

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?

like image 886
hhh Avatar asked Feb 22 '12 07:02

hhh


People also ask

How do you find the index of the minimum element of a vector?

To find the largest or smallest element stored in a vector, you can use the methods std::max_element and std::min_element , respectively. These methods are defined in <algorithm> header. If several elements are equivalent to the greatest (smallest) element, the methods return the iterator to the first such element.

How do you find the smallest element in a vector?

To find a smallest or minimum element of a vector, we can use *min_element() function which is defined in <algorithm> header. It accepts a range of iterators from which we have to find the minimum / smallest element and returns the iterator pointing the minimum element between the given range.

How do you find the minimum index?

Python inbuilt function allows us to find it in one line, we can find the minimum in the list using the min() function and then us index() function to find out the index of that minimum element.

How do you find the index of a minimum value in R?

Return the Index of the First Minimum Value of a Numeric Vector in R Programming – which. min() Function. which. min() function in R Language is used to return the location of the first minimum value in the Numeric Vector.


1 Answers

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

like image 153
Josh O'Brien Avatar answered Sep 17 '22 13:09

Josh O'Brien