overwhelmed overwhelmed - 2 months ago 9
R Question

How to identify the position of the first minimum in a vector?

Say I have the following vector:

y
[1] 10
[2] 9
[3] 8
[4] 6
[5] 7
[6] -3
[7] -1


Though the position of the minimum can be get using
which(y==min(y)
as 6. But I want to know how to get the first minimum which is
6
and the position is
4
. After 6 the value increased to 7.
Thanks in advance.

Answer

Try:

first.min <- function(y) {
  d <- which(diff(y) > 0)
  if (length(d) > 0) d[1] else NA
}
first.min(y)
##[1] 4

This gives you the position. To get the minimum value:

y[first.min(y)]
##[1] 6