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